UFO ET IT

높이와 너비가 아닌 UIImage의 크기 (바이트 길이) 가져 오기

ufoet 2020. 12. 14. 20:25
반응형

높이와 너비가 아닌 UIImage의 크기 (바이트 길이) 가져 오기


나는 UIImage. 이미지의 너비 나 높이가 아니라 데이터의 크기입니다.


의 기본 데이터 UIImage는 다를 수 있으므로 동일한 "이미지"에 대해 다양한 크기의 데이터를 가질 수 있습니다. 당신이 할 수있는 한 가지는 둘 중 하나에 대해 동등한 구조를 사용 UIImagePNGRepresentation하거나 UIImageJPEGRepresentation얻은 NSData다음 그 크기를 확인하는 것입니다.


 UIImage *img = [UIImage imageNamed:@"sample.png"];
 NSData *imgData = UIImageJPEGRepresentation(img, 1.0); 
 NSLog(@"Size of Image(bytes):%d",[imgData length]);

UIImage의 CGImage 속성을 사용합니다. 그런 다음 CGImageGetBytesPerRow *
CGImageGetHeight 의 조합을 사용하여 UIImage의 크기를 추가하면 실제 크기의 몇 바이트 내에 있어야합니다.

이것은 비트 맵 조작을 준비하기 위해 malloc과 같은 목적으로 사용하려는 경우 압축되지 않은 이미지의 크기를 반환합니다 (RGB의 경우 3 바이트, 알파의 경우 1의 4 바이트 픽셀 형식으로 가정).

int height = image.size.height,
    width = image.size.width;
int bytesPerRow = 4*width;
if (bytesPerRow % 16)
    bytesPerRow = ((bytesPerRow / 16) + 1) * 16;
int dataSize = height*bytesPerRow;

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)editInfo
{
   UIImage *image=[editInfo valueForKey:UIImagePickerControllerOriginalImage];
   NSURL *imageURL=[editInfo valueForKey:UIImagePickerControllerReferenceURL];
   __block long long realSize;

   ALAssetsLibraryAssetForURLResultBlock resultBlock=^(ALAsset *asset)
   {
      ALAssetRepresentation *representation=[asset defaultRepresentation];
      realSize=[representation size];
   };

   ALAssetsLibraryAccessFailureBlock failureBlock=^(NSError *error)
   {
      NSLog(@"%@", [error localizedDescription]);
   };

   if(imageURL)
   {
      ALAssetsLibrary *assetsLibrary=[[[ALAssetsLibrary alloc] init] autorelease];
      [assetsLibrary assetForURL:imageURL resultBlock:resultBlock failureBlock:failureBlock];
   }
}

Swift의:

let img: UIImage? = UIImage(named: "yolo.png")
let imgData: NSData = UIImageJPEGRepresentation(img, 0)
println("Size of Image: \(imgData.length) bytes")

다음은 답을 얻는 가장 빠르고 깨끗하며 가장 일반적이며 오류 발생 가능성이 가장 적은 방법입니다. 카테고리에서 UIImage+MemorySize:

#import <objc/runtime.h>

- (size_t) memorySize
{
  CGImageRef image = self.CGImage;
  size_t instanceSize = class_getInstanceSize(self.class);
  size_t pixmapSize = CGImageGetHeight(image) * CGImageGetBytesPerRow(image);
  size_t totalSize = instanceSize + pixmapSize;
  return totalSize;
}

또는 UIImage 인스턴스 컨테이너가 아닌 실제 비트 맵 만 원하는 경우 다음과 같이 간단합니다.

- (size_t) memorySize
{
  return CGImageGetHeight(self.CGImage) * CGImageGetBytesPerRow(self.CGImage);
}

귀하의 상황을 잘 모르겠습니다. 실제 바이트 크기가 필요하면 그렇게 생각하지 않습니다. UIImagePNGRepresentation 또는 UIImageJPEGRepresentation을 사용하여 이미지 압축 데이터의 NSData 객체를 가져올 수 있습니다.

I think you want to get the actual size of uncompressed image(pixels data). You need to convert UIImage* or CGImageRef to raw data. This is an example of converting UIImage to IplImage(from OpenCV). You just need to allocate enough memory and pass the pointer to CGBitmapContextCreate's first arg.

UIImage *image = //Your image
CGImageRef imageRef = image.CGImage;

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
IplImage *iplimage = cvCreateImage(cvSize(image.size.width, image.size.height), IPL_DEPTH_8U, 4);
CGContextRef contextRef = CGBitmapContextCreate(iplimage->imageData, iplimage->width, iplimage->height,
                                                iplimage->depth, iplimage->widthStep,
                                                colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault);
CGContextDrawImage(contextRef, CGRectMake(0, 0, image.size.width, image.size.height), imageRef);
CGContextRelease(contextRef);
CGColorSpaceRelease(colorSpace);

IplImage *ret = cvCreateImage(cvGetSize(iplimage), IPL_DEPTH_8U, 3);
cvCvtColor(iplimage, ret, CV_RGBA2BGR);
cvReleaseImage(&iplimage);

Swift 3:

let image = UIImage(named: "example.jpg")
if let data = UIImageJPEGRepresentation(image, 1.0) {
    print("Size: \(data.count) bytes")
}

If needed in human readable form we can use ByteCountFormatter

if let data = UIImageJPEGRepresentation(image, 1.0) {
   let fileSizeStr = ByteCountFormatter.string(fromByteCount: Int64(data.count), countStyle: ByteCountFormatter.CountStyle.memory)
   print(fileSizeStr)
}

Where Int64(data.count) is what you need in numeric format.


SWIFT 4+

let imgData = image?.jpegData(compressionQuality: 1.0)
debugPrint("Size of Image: \(imgData!.count) bytes")

you can use this trick to find out image size.

참고URL : https://stackoverflow.com/questions/1296707/get-size-of-a-uiimage-bytes-length-not-height-and-width

반응형