Reputation: 2687
I try to use UIImageView
to show the photo. But the Photo sometimes is a little large, and I want to compress it.But I'd like to keep its size.
For example,a photo is 4M and has a size of 320X480. And I want to compress it and it may have 1M but still has a size of 320X480.
thanks!
Upvotes: 3
Views: 10059
Reputation: 623
If your goal is to get the image below a specific data length, it's tough to guess what compression ratio you need, unless you know the source image will always be a certain data length. Here's a simple iterative approach that uses jpeg compression to achieve a target length... let's say 1MB, to match the question:
// sourceImage is whatever image you're starting with
NSData *imageData = [[NSData alloc] init];
for (float compression = 1.0; compression >= 0.0; compression -= .1) {
imageData = UIImageJPEGRepresentation(sourceImage, compression);
NSInteger imageLength = imageData.length;
if (imageLength < 1000000) {
break;
}
}
UIImage *finalImage = [UIImage imageWithData:imageData];
I've seen some approaches that use a while
loop to compresses the image by .9 or whatever until the target size is met, but I think you'd be losing image quality and processor cycles by successively compressing/reconstituting the image. Also, the for
loop here is a little safer because it stops automatically after trying the maximum possible compression (zero).
Upvotes: 3
Reputation: 32681
Compress it using the JPEG compression.
lowResImage = [UIImage imageWithData:UIImageJPEGRepresentation(highResImage, quality)];
Where quality is between 0.0 and 1.0
You should read the UIImage documentation, everything is explained in there…
Upvotes: 18