图片的压缩方式

引言

在我们项目开发中我们经常会遇到关于图片的处理。

在图片上传中我们会从用户体验方面考虑用户的流量是否能够很好的支持上传的图片,我们会对图片先压缩后上传。

当我们考虑到手机的本身内存我们会对下载的图片进行压缩,以便节省手机内存成本。

读取图片的方式

1
2
1、UIImageJPEGRepresentation()此API需要两个参数,一个是图片对象,一个是压缩系数,但是图片的质量会有所下降,但是体积不会变。
2、UIImagePNGRepresentation(),只需要一个图片的对象参数,不会对图片压缩,原图展示。

对图片的质量进行压缩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
1、UIImageJPEGRepresentation()返回的数据量要比UIImagePNGRepresentation()大很多,前者返回的数据量要比后者小很多,前者返回的数据量大概是115kb,后者返回的数据大概为190kb,相差很大。
2、如果对UIImageJPEGRepresentation()的系数设置为0.5,再加上本身不是很追求图片的质量,那么会大大节省图片的资源大小,大概为11kb。
+ (UIImage *)resuceImage:(UIImage *)hdfImage percent:(CGFloat)percent {
UIImage *image = nil;
NSData *data = nil;
if(hdfImage) {
data = UIImageJPEGRepresentation(hdfImage, percent);
image = [UIImage imageWithData:data];
}
return image;
}

压缩图片到指定的尺寸

我们传入理想的图片尺寸即可。

1
2
3
4
5
6
7
8
9
10
11
+ (UIImage *)reduceImage:(UIImge *)hdfImage reduceSize:(CGSize)reduceSize {
UIGraphicsBeginImageContext(reduceSize);
UIIMage *image = nil;
if(hdfImage) {
[image drawInRect:CGRectMake(0, 0, reduceSize.width, reducdeSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return image;
}

等比例压缩图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
-(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth {
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = defineWidth;
CGFloat targetHeight = height / (width / targetWidth);
CGSize size = CGSizeMake(targetWidth, targetHeight);
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
if(CGSizeEqualToSize(imageSize, size) == NO){
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;
if(widthFactor > heightFactor){
scaleFactor = widthFactor;
}
else{
scaleFactor = heightFactor;
}
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
if(widthFactor > heightFactor){
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}else if(widthFactor < heightFactor){
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
UIGraphicsBeginImageContext(size);
CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil){
NSLog(@"scale image fail");
}
UIGraphicsEndImageContext();
return newImage;
}