gpt4 book ai didi

ios - NSData到UIImage的质量

转载 作者:行者123 更新时间:2023-12-01 16:24:12 27 4
gpt4 key购买 nike

我使用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

这是图片的 图片

最佳答案

我不知道为什么,但是您可以像这样重新绘制图像:

+(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;

}

关于ios - NSData到UIImage的质量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40524676/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com