获取 UIImage 的大小(字节长度)而不是高度和宽度

发布于 2024-08-02 04:29:35 字数 59 浏览 1 评论 0原文

我正在尝试获取 UIImage 的长度。不是图像的宽度或高度,而是数据的大小。

I'm trying to get the length of a UIImage. Not the width or height of the image, but the size of the data.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

一笔一画续写前缘 2024-08-09 04:29:35
 UIImage *img = [UIImage imageNamed:@"sample.png"];
 NSData *imgData = UIImageJPEGRepresentation(img, 1.0); 
 NSLog(@"Size of Image(bytes):%d",[imgData length]);
 UIImage *img = [UIImage imageNamed:@"sample.png"];
 NSData *imgData = UIImageJPEGRepresentation(img, 1.0); 
 NSLog(@"Size of Image(bytes):%d",[imgData length]);
冷默言语 2024-08-09 04:29:35

UIImage 的基础数据可能会有所不同,因此对于同一“图像”,可以具有不同大小的数据。您可以做的一件事是使用 UIImagePNGRepresentationUIImageJPEGRepresentation 获取两者的等效 NSData 构造,然后检查其大小。

The underlying data of a UIImage can vary, so for the same "image" one can have varying sizes of data. One thing you can do is use UIImagePNGRepresentation or UIImageJPEGRepresentation to get the equivalent NSData constructs for either, then check the size of that.

锦上情书 2024-08-09 04:29:35

使用 UIImage 的 CGImage 属性。然后结合使用CGImageGetBytesPerRow *
CGImageGetHeight,添加UIImage的大小,应该在实际大小的几个字节之内。

如果您想将其用于诸如 malloc 之类的目的,这将返回未压缩的图像大小,以准备位图操作(假设 4 字节像素格式为 3 字节用于 RGB,1 字节用于 Alpha):

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;

Use the CGImage property of UIImage. Then using a combination of CGImageGetBytesPerRow *
CGImageGetHeight, add in the sizeof UIImage, you should be within a few bytes of the actual size.

This will return the size of the image, uncompressed, if you want to use it for purposes such as malloc in preparation for bitmap manipulation (assuming a 4 byte pixel format of 3 bytes for RGB and 1 for Alpha):

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;
半衬遮猫 2024-08-09 04:29:35
- (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];
   }
}
- (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];
   }
}
稚然 2024-08-09 04:29:35

Swift 中的示例:

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

Example in Swift:

let img: UIImage? = UIImage(named: "yolo.png")
let imgData: NSData = UIImageJPEGRepresentation(img, 0)
println("Size of Image: \(imgData.length) bytes")
陈甜 2024-08-09 04:29:35

以下是获得答案的最快、最干净、最通用且最不容易出错的方法。在类别 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);
}

This following is the fastest, cleanest, most general, and least error-prone way to get the answer. In a category 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;
}

Or if you only want the actual bitmap and not the UIImage instance container, then it is truly as simple as this:

- (size_t) memorySize
{
  return CGImageGetHeight(self.CGImage) * CGImageGetBytesPerRow(self.CGImage);
}
梦里人 2024-08-09 04:29:35

斯威夫特3:

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

Swift 3:

let image = UIImage(named: "example.jpg")
if let data = UIImageJPEGRepresentation(image, 1.0) {
    print("Size: \(data.count) bytes")
}
清风不识月 2024-08-09 04:29:35

斯威夫特 4 & 5:

extension UIImage {
    var sizeInBytes: Int {
        guard let cgImage = self.cgImage else {
            // This won't work for CIImage-based UIImages
            assertionFailure()
            return 0
        }
        return cgImage.bytesPerRow * cgImage.height
    }
}

Swift 4 & 5:

extension UIImage {
    var sizeInBytes: Int {
        guard let cgImage = self.cgImage else {
            // This won't work for CIImage-based UIImages
            assertionFailure()
            return 0
        }
        return cgImage.bytesPerRow * cgImage.height
    }
}
帅气称霸 2024-08-09 04:29:35

我不确定你的情况。如果您需要实际的字节大小,我认为您不会这样做。您可以使用 UIImagePNGRepresentation 或 UIImageJPEGRepresentation 来获取图像压缩数据的 NSData 对象。

我想你想获得未压缩图像的实际大小(像素数据)。您需要将 UIImage* 或 CGImageRef 转换为原始数据。这是将 UIImage 转换为 IplImage(来自 OpenCV)的示例。您只需要分配足够的内存并将指针传递给 CGBitmapContextCreate 的第一个参数。

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);

I'm not sure your situation. If you need the actual byte size, I don't think you do that. You can use UIImagePNGRepresentation or UIImageJPEGRepresentation to get an NSData object of compressed data of the image.

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);
紫南 2024-08-09 04:29:35

SWIFT 4+

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

您可以使用此技巧来找出图像大小。

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.

記憶穿過時間隧道 2024-08-09 04:29:35

我尝试使用获取图像大小

let imgData = image.jpegData(compressionQuality: 1.0)

,但它给出的图像大小小于图像的实际大小。然后我尝试使用 PNG 表示来获取大小。

let imageData = image.pngData()

但它给出的字节数比实际图像大小更多。

唯一对我来说完美的东西

public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    var asset: PHAsset!
    if #available(iOS 11.0, *) {
      asset = info[UIImagePickerControllerPHAsset] as? PHAsset
    } else {
      if let url = info[UIImagePickerControllerReferenceURL] as? URL {
        asset = PHAsset.fetchAssets(withALAssetURLs: [url], options: .none).firstObject!
      }
    }

    if #available(iOS 13, *) {
      PHImageManager.default().requestImageDataAndOrientation(for: asset, options: .none) { data, string, orien, info in
        let imgData = NSData(data:data!)
        var imageSize: Int = imgData.count
        print("actual size of image in KB: %f ", Double(imageSize) / 1024.0)
      }
    } else {
      PHImageManager.default().requestImageData(for: asset, options: .none) { data, string, orientation, info in
        let imgData = NSData(data:data!)
        var imageSize: Int = imgData.count
        print("actual size of image in KB: %f ", Double(imageSize) / 1024.0)
      }
    }
  }

I tried to get image size using

let imgData = image.jpegData(compressionQuality: 1.0)

but it gives less than the actual size of image. Then i tried to get size using PNG representation.

let imageData = image.pngData()

but it gives more byte counts than the actual image size.

The only thing that worked perfectly for me.

public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    var asset: PHAsset!
    if #available(iOS 11.0, *) {
      asset = info[UIImagePickerControllerPHAsset] as? PHAsset
    } else {
      if let url = info[UIImagePickerControllerReferenceURL] as? URL {
        asset = PHAsset.fetchAssets(withALAssetURLs: [url], options: .none).firstObject!
      }
    }

    if #available(iOS 13, *) {
      PHImageManager.default().requestImageDataAndOrientation(for: asset, options: .none) { data, string, orien, info in
        let imgData = NSData(data:data!)
        var imageSize: Int = imgData.count
        print("actual size of image in KB: %f ", Double(imageSize) / 1024.0)
      }
    } else {
      PHImageManager.default().requestImageData(for: asset, options: .none) { data, string, orientation, info in
        let imgData = NSData(data:data!)
        var imageSize: Int = imgData.count
        print("actual size of image in KB: %f ", Double(imageSize) / 1024.0)
      }
    }
  }
冰火雁神 2024-08-09 04:29:35

如果需要人类可读的形式,我们可以使用 ByteCountFormatter

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

其中 Int64(data. count) 是您需要的数字格式。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文