Image reduction without affecting the quality of the lens c

How to compress an image without affecting the quality programmatically.

After capturing an image, I want to reduce the size of this image without changing the quality in objective-c.

+5
source share
2 answers

Here is the code I used to compress the image

Code:

-(UIImage *)compressImage:(UIImage *)image{ NSData *imgData = UIImageJPEGRepresentation(image, 1); //1 it represents the quality of the image. NSLog(@"Size of Image(bytes):%ld",(unsigned long)[imgData length]); float actualHeight = image.size.height; float actualWidth = image.size.width; float maxHeight = 600.0; float maxWidth = 800.0; float imgRatio = actualWidth/actualHeight; float maxRatio = maxWidth/maxHeight; float compressionQuality = 0.5;//50 percent compression if (actualHeight > maxHeight || actualWidth > maxWidth){ if(imgRatio < maxRatio){ //adjust width according to maxHeight imgRatio = maxHeight / actualHeight; actualWidth = imgRatio * actualWidth; actualHeight = maxHeight; } else if(imgRatio > maxRatio){ //adjust height according to maxWidth imgRatio = maxWidth / actualWidth; actualHeight = imgRatio * actualHeight; actualWidth = maxWidth; } else{ actualHeight = maxHeight; actualWidth = maxWidth; } } CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight); UIGraphicsBeginImageContext(rect.size); [image drawInRect:rect]; UIImage *img = UIGraphicsGetImageFromCurrentImageContext(); NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality); UIGraphicsEndImageContext(); NSLog(@"Size of Image(bytes):%ld",(unsigned long)[imageData length]); return [UIImage imageWithData:imageData]; } 

So here is the code to use above

 UIImage *org = [UIImage imageNamed:@"MacLehose Stage 7 Stunning Natural Sceneries.jpg"]; UIImage *imgCompressed = [self compressImage:org]; 

If you want to squeeze more

 NSData *dataImage = UIImageJPEGRepresentation(imgCompressed, 0.0); NSLog(@"Size of Image(bytes):%ld",(unsigned long)[dataImage length]); 

In the above way, I can compress the image from 2 MB to almost 50 KB.

+8
source

I know a lot about this topic. A few days later I found this. Hope this is much faster than the accepted answer.

 NSData *imageData; imageData=[[NSData alloc] initWithData:UIImageJPEGRepresentation((chosenImage), 1.0)]; NSLog(@"[before] image size: %lu--", (unsigned long)[imageData length]); CGFloat scale= (100*1024)/(CGFloat)[imageData length]; // For 100KB. UIImage *small_image=[UIImage imageWithCGImage:chosenImage.CGImage scale:scale orientation:chosenImage.imageOrientation]; imageData = UIImageJPEGRepresentation(small_image, scale*1.00); NSLog(@"[after] image size: %lu:%f", (unsigned long)[imageData length],scale); 

It worked fine for me !. Try it once.

+3
source

Source: https://habr.com/ru/post/1258460/


All Articles