以分割一张JPG的图片为例,此方法可以将图片均等分割成想要的数量,也可以从任意位置进行对图片的分割,抛砖引玉,大家且看代码吧。
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
|
UIImage *image = [UIImage imageNamed:@"apple.jpg"];
float fxw = image.size.width*1.0/2; // “2”X方向分割的数量
float xyh = image.size.height*1.0/2; //“2”Y方向分割的数量
for(int i = 0 ; i < 2 ; i++){
for(int j = 0 ; j < 2 ; j++){
CGRect rect = CGRectMake(i*fxw, j*xyh, fxw, xyh); //定义出重回的举行区域
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *imageIn = [UIImage imageWithCGImage:imageRef];
NSString *str = [NSString stringWithFormat:@"apple_%d_%d.jpg",i,j];
NSString *stri = [NSHomeDirectory() stringByAppendingPathComponent:str];
NSLog(@"%@",stri);
NSData *data = UIImageJPEGRepresentation(imageIn, 0.5);
[data writeToFile:stri atomically:NO]; //写入到路径
}
}
|
CGImageRef 与 CGImage 用于重绘操作
在Iphone上有两种读取图片数据的简单方法: UIImageJPEGRepresentatio
n和UIImagePNGRepresentation. UIImageJPEGRepresentation函数需要两个参数:图片的引用和压缩系数.而UIImagePNGRepresentation只需要图片引用作为参数.通过在实际使用过程中,比较发现: UIImagePNGRepresentation(UIImage* image) 要比UIImageJPEGRepresentation(UIImage* image, 1.0) 返回的图片数据量大很多.譬如,同样是读取摄像头拍摄的同样景色的照片,
UIImagePNGRepresentation()返回的数据量大小为199K ,而 UIImageJPEGRepresentation(UIImage* image, 1.0)返回的数据量大小只为140KB,比前者少了50多KB.如果对图片的清晰度要求不高,还可以通过设置 UIImageJPEGRepresentation函数的第二个参数,大幅度降低图片数据量.譬如,刚才拍摄的图片, 通过调用UIImageJPEGRepresentation(UIImage* image,
1.0)读取数据时,返回的数据大小为140KB,但更改压缩系数后,通过调用UIImageJPEGRepresentation(UIImage* image, 0.5)读取数据时,返回的数据大小只有11KB多,大大压缩了图片的数据量 ,而且从视角角度看,图片的质量并没有明显的降低.因此,在读取图片数据内容时,建议优先使用UIImageJPEGRepresentation,并可根据自己的实际使用场景,设置压缩系数,进一步降低图片数据量大小.