I have code to recreate a high quality image at a very poor quality but I am a bit confused by the results I am seeing. The code is here:
NSData *compressedData = UIImageJPEGRepresentation(bigImage,0);
NSLog(@"compressedData length = %d", [compressedData length]);
self.currentImage = [UIImage imageWithData:compressedData];
NSData *dataAfterCompression = UIImageJPEGRepresentation(self.currentImage,1);
NSLog(@"dataAfterCompression length = %d", [dataAfterCompression length]);
Which outputs:
2012-01-02 02:47:05.615 MyApp[349:707] compressedData length = 32671
2012-01-02 02:47:06.143 MyApp[349:707] dataAfterCompression length = 251144
Why would creating a new image with the low quality data result in such a large image?
Create an extension Reduce the image height so it becomes smaller and uses less space. Create a new file called Extensions. swift and import SwiftUI at the top. Then, create an extension for UIImage, called aspectFittedToHeight, which will take a newHeight and return a smaller UIImage.
An object that manages image data in your app.
The input to UIImageJPEGRepresentation
is a 2-D array of pixels, not the compressed data from which that 2-D array was created. (The array might not have come from compressed data at all!) UIImageJPEGRepresentation
doesn't know anything about where the image came from, and it doesn't have any concept of the "quality" of its input. It just knows that you want it to try very hard to make the output small (when compressionQuality
is zero) or you want it to try very hard to make the output accurate (when compressionQuality
is one).
The JPEG compression algorithm has some tunable parameters. The compressionQuality
value selects a set of those parameters. When you set compressionQuality
to 1, the compressor uses a set of parameters that allow very little loss of accuracy of the input data, regardless of what that input data actually is. For any input data, those parameters result in very little loss of accuracy. The tradeoff is that those parameters also result in very little compression. The compressor doesn't then think "Hmm, I should try using other parameters and see if I get the same accuracy with better compression". If that's what you want, you have to do it yourself.
I am not sure if this is exactly what you are looking for, but this blog has some classes that extend UIImage and it deals with compression quite nice. Check out this website: http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With