我们在开发中会遇到很多的图片处理问题,像图片的压缩处理,来看一下iOS中图片的压缩处理:
对于图片压的功能,我们可以使用UIImageJPEGRepresentation或UIImagePNGRepresentation方法实现,UIImageJPEGRepresentation函数需要两个参数:图片的引用和压缩系数而UIImagePNGRepresentation只需要图片引用作为参数,压缩系数不宜太低,通常是0.3~0.7,过小则可能会出现黑边等。如果对图片的清晰度要求不是极高,建议使用UIImageJPEGRepresentation,可以大幅度降低图片数据量,而且清晰度并没有相差多少,图片的质量并没有明显的降低。
UIImage *image1 = [UIImage imageNamed:@"美女.jpg"];
NSData *img1Data = UIImageJPEGRepresentation(image1, 0.5);
NSLog(@"img1Data %@",img1Data);
UIImage *image2 = [UIImage imageNamed:@"2"];
NSData *img2Data = UIImagePNGRepresentation(image2);
NSLog(@"img2Data %@",img2Data);
//然后通过下面方法重新获得图片
UIImage *image = [UIImage imageWithData: img1Data];
//再来看一下图片的缩小处理
CGSize imageSize = image.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetHeight = (targetWidth / width) * height;
UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
//利用 drawInRect:CGRectMake(0, 0, targetWidth, targetHeight) 重新获得图片
[sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();