NSData到UIImage的质量

时间:2016-11-10 10:00:20

标签: ios objective-c uiimage nsdata

我使用的是UIImage *image = [UIImage imageWithData: data],但图片的尺寸要大四倍。原始 data.length = 100 KB ,但此图片现在有超过400 KB。您可能会说要完成压缩。但是我在压缩 data.length = 200 KB 之后通过以下方法。

以下是我的方式

压缩方法

 // spend is size (KB)
    - (NSData *)compressionImageData:(NSData *)data spend:(CGFloat)spend {

        if (data.length < spend) {
            return data;    //no compression
        }
        UIImage *sourceImg = [UIImage imageWithData:data];

        CGFloat compression = 0.9f;
        CGFloat maxCompression = 0.1f;
        NSData *imageData = UIImageJPEGRepresentation(sourceImg, compression);

        while ([imageData length] > spend && compression > maxCompression) {
            compression -= 0.1;
            imageData = UIImageJPEGRepresentation(sourceImg, compression);
        }
        return imageData; 
    }

下载图片方法:

- (void)loadPosterImage:(NSString *)imgURL {
    weakSelf();
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:imgURL]
            options:SDWebImageDownloaderLowPriority
            progress:^(NSInteger receivedSize, NSInteger expectedSize) {}
            completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                strongSelf();
                //  image is through [UIImage imageWithData: data]
                self.posterImage = image;
                self.posterData = data;

            }];
}

图片大小超过500 KB

data.lenght = 100KB

这是图片的 data.length

https://i.stack.imgur.com/FzUvk.png

这是图片的图片

https://i.stack.imgur.com/ozxa6.png

1 个答案:

答案 0 :(得分:0)

我不知道为什么,但你可以像这样重绘图像:

+(NSData *)compressDataWithImage:(UIImage *)image toMaxFIleSize:(NSInteger)maxFileSize {
UIImage *comImage;

comImage = image;
CGFloat compression = 1.0;
NSData *imageData = UIImageJPEGRepresentation(comImage, compression);
NSData *newData;
while (imageData.length > maxFileSize) {
    compression *= 0.5;
    newData = UIImageJPEGRepresentation(comImage, compression);
    if (newData.length == imageData.length) {
        CGSize newSize = CGSizeMake(comImage.size.width * 0.5, comImage.size.height * 0.5);
        UIGraphicsBeginImageContext(newSize);
        [comImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        comImage = UIGraphicsGetImageFromCurrentImageContext();
        newData = UIImageJPEGRepresentation(comImage, compression);
    }
    imageData = newData;
  }

return imageData;

}