首页 技术 正文
技术 2022年11月14日
0 收藏 887 点赞 3,104 浏览 1487 个字

最近做图片的上传,由于项目中的涉及到的图片是从相册和相机中拍照获取的,所以图片的类型不一定,有些是jpg有些是png,另外随着现在设备相继的像素越来越高,所拍摄的图片也越来越到,在图片上传之前我们是需要进行一定的处理的。最常见的是1.缩小图片的尺寸。2:降低图片的质量。针对以上两种方法,我编写了一个UIImage的Category.代码如下:

//

//  UIImage+Resize.h

//  hjclass

//

//  Created by alan chen on 14-4-17.

//  Copyright (c) 2014年 alan chen. All rights reserved.

//

#import <UIKit/UIKit.h>

@interface UIImage (Resize)

– (UIImage*)scaleToSize:(CGSize)size;

– (UIImage*)compressToCompressent:(float)compress;

@end

//

//  UIImage+Resize.m

//  hjclass

//

//  Created by alan chen on 14-4-17.

//  Copyright (c) 2014年 alan chen. All rights reserved.

//

#import “UIImage+Resize.h”

@implementation UIImage (Resize)

– (UIImage*)scaleToSize:(CGSize)size{

UIGraphicsBeginImageContext(size);//创建bitmap的context 并设置当前使用的context

[self drawAsPatternInRect:CGRectMake(0, 0, size.width, size.height)];//在指定的区域绘制图片

UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();//从当前context中获取压缩后的image

UIGraphicsEndImageContext(); //将当前的context从堆栈中退出

return scaledImage;

}

– (UIImage*)compressToCompressent:(float)compress{

NSData *data;//判断图片是不是png格式的文件

if(UIImagePNGRepresentation(self)){

data = UIImagePNGRepresentation(self);//png格式是不能够压缩的

}else{

data = UIImageJPEGRepresentation(self, compress);

}

return [UIImage imageWithData: data];

}

@end

这个Category中有两个方法,分别用于压缩图片的大小和图片的质量,对于压缩图片的大小我们在项目中一般建议进行等比压缩,保证图片在视觉上不变形,压缩图片的大小能够快速的降低图片的大小。一般大小压缩比大约为scale*scale,也就是长宽压缩比之积。令外对于质量压缩,很多资料建议压缩比大于8.但是我在实际情况中采用压缩比大于8也没有看到非常明显的失真。我们一般从1.0压缩到0.5,图片的大小将会压缩到原来的1/8-1/9.但是在0.5压缩到0.2的时候,图片的大小只会减少1/2左右。所以从0.5到0.2的压缩效果不如1.0到0.5那么明显。那么其实我们在项目开发过程中我们一般将图片压缩到100k以内就可以了。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,093
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,569
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,417
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,190
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,825
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,908