我想压缩UIImage。然而,我得到了一个错误的尺寸。我肯定UIImageJPEGRepresentation会为我糟糕的英语而道歉的wrong.how
+ (NSData *)compressDataWithImg:(UIImage *)originalImage compression:(CGFloat)compression size:(CGFloat)size {
NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(originalImage, compression)];
if ((data.length / 1024.0) > size)
{
compression = compression - 0.1;
if (compression > 0) {
return [[self class] compressDataWithImg:originalImage compression:compression size:(CGFloat)size];
}else{
return data;
}
}else{
return data;
}
return data;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *fullImage = info[UIImagePickerControllerOriginalImage];
fullImage = [fullImage fixOrientationToUp];
UIImage *imgData = [fullImage scaleToSizeWithLimit:0];
NSData *data = [Util compressDataWithImg:imgData compression:0.9 size:256]; // this is right:size:2M
UIImage *image = [UIImage imageWithData:data];//i use this UIImage
NSData *xxx = [NSData dataWithData: UIImageJPEGRepresentation(image,1) ];// wrong size:7~8M WHY?...
if (self.imageSelectBlock) {
self.imageSelectBlock(image);
}
[picker dismissViewControllerAnimated:YES completion:NULL] ;
}谢谢你帮我
发布于 2017-08-04 17:07:02
我发现当我使用UIImageJPEGRepresentation和imageWithData时,会一次又一次地处理图像。图像数据的length逐渐增加。
测试代码:
UIImage *image = [UIImage imageNamed:@"test.png"];
NSLog(@"first: %lu", UIImageJPEGRepresentation(image, 1.0).length);
NSLog(@"second: %lu", UIImageJPEGRepresentation([UIImage imageWithData:UIImageJPEGRepresentation(image, 1.0)], 1.0).length);
NSLog(@"third: %lu", UIImageJPEGRepresentation([UIImage imageWithData:UIImageJPEGRepresentation([UIImage imageWithData:UIImageJPEGRepresentation(image, 1.0)], 1.0)], 1.0).length);日志:
first: 361586
second: 385696
third: 403978我认为这个问题是由UIImageJPEGRepresentation引起的。
这只是个测试。
我发现了一个相关的问题:
https://stackoverflow.com/questions/45500865
复制相似问题