缩小图像而不影响目标c的质量

时间:2016-10-19 10:46:55

标签: ios objective-c image shrink

如何缩小图像而不会以编程方式影响质量。

捕获图像后,我想减小图像的大小而不改变objective-c的质量。

2 个答案:

答案 0 :(得分:7)

这是我用过的压缩图像的代码

代码:

-(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];
}

以下是使用上述

的代码
UIImage *org = [UIImage imageNamed:@"MacLehose Stage 7 Stunning Natural Sceneries.jpg"];

UIImage *imgCompressed = [self compressImage:org];

如果你想压缩更多

NSData *dataImage = UIImageJPEGRepresentation(imgCompressed, 0.0);

NSLog(@"Size of Image(bytes):%ld",(unsigned long)[dataImage length]);

通过上述方式,我能够将图像从2 MB压缩到接近约50 KB

希望这有帮助

快乐的编码......

答案 1 :(得分:3)

我经常搜索这个主题。几天后,我找到了这个。希望这比接受的答案快得多。

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

这对我很有用!尝试一次。