Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get exact size of image in bytes?

I have calculated image size in bytes by converting image into NSData and its data length got wrong value.

    NSData *data = UIImageJPEGRepresentation(image,0.5);
    NSLog(@"image size in bytes %lu",(unsigned long)data.length);
like image 242
Nagendra Avatar asked May 29 '14 05:05

Nagendra


People also ask

What size image is 1.5 MB?

1.5mb – 2mb up to A5 – half A4 (148 x 210 mm or 5⅞” x 8¼”) 3.5mb up to A4 (210 x 297 mm or 8¼” x 11¾”)


1 Answers

Actually, the UIImage.length function here is not returning the wrong value, its just the result of the lossy conversion/reversion from a UIImage to NSData.

Setting the compressionQuality to the lowest compression possible of 1.0 in UIImageJpegRepresentation will not return the original image. Although the image metadata is stripped in this process, the function can and usually will yield an object larger than the original. Note that this increase in filesize does NOT increase the quality of the image from the compressed original either. Jpegs are highly compressed to begin with, which is why they are used so often, and the function is uncompressing it and then recompressing it. Its kind of like getting botox after age has stretched your body out, it might look similar to the original, but the insides are just not as as good as they used to be.

You could use a lower compressionQuality conditionally on larger files, close to 1.0, as the quality will drop off quickly. Other than that, depending on the final purpose of your images, the only other option would be to resize the image or adjust its resolution, perhaps in addition to adjusting the compression ratio. This change will exponentially curtail data usage. Web and mobile usage typically don't need the resolution as something like images meant for digital print.

You can write some code that adjusts each image and NSData representation only as much as needed to fit its individual data constraint.

like image 169
Ataraxia64 Avatar answered Oct 04 '22 18:10

Ataraxia64