图片分割的代码

本文介绍了一个Objective-C方法,用于将一张大图片按指定行列数切割成多张小图片,并保存到本地。该方法适用于需要对图片进行处理的应用场景,如添加百叶窗效果或制作拼图游戏。

/*

 +(NSDictionary*)SeparateImage:(UIImage*)image ByX:(int)x andY:(int)y cacheQuality:(float)quality;

 方法说明:

 NSDictionary*:返回字典,UIImageView格式,不仅含有 Image 还含有 Rect

 image: 图片资源,要求为UIImage格式。x: y:分别表示要切成几行和列,最小值为1

 quality:处理后保存的小图片的质量。(01]有效,小于或为0不保存,大于1时会被强强制为1

 切割后的小图片保存位置为 Homedirectory 可以通过 nslog(@"%@",NSHomedirectory()); 查出。

 

 用途:

 适合图片处理应用里为图片添加百叶窗效果,或者拼图游戏里...

 */

 

 

+(NSDictionary*)SeparateImage:(UIImage*)image ByX:(int)x andY:(int)y cacheQuality:(float)quality

{

//kill errors

if (x<1) {

NSLog(@"illegal x!");

return nil;

}else if (y<1) {

NSLog(@"illegal y!");

return nil;

}

if (![image isKindOfClass:[UIImage class]]) {

NSLog(@"illegal image format!");

return nil;

}

//attributes of element

float _xstep=image.size.width*1.0/(y+1);

float _ystep=image.size.height*1.0/(x+1);

NSMutableDictionary*_mutableDictionary=[[[NSMutableDictionary alloc]initWithCapacity:1]autorelease];

//NSArray*_array=[imageName componentsSeparatedByString:@"."];

//NSString*prefixName=[_array objectAtIndex:0];

NSString*prefixName=@"win";

//snap in context and create element image view

for (int i=0; i<x; i++) 

{

for (int j=0; j<y; j++) 

{

CGRect rect=CGRectMake(_xstep*j, _ystep*i, _xstep, _ystep);

CGImageRef imageRef=CGImageCreateWithImageInRect([image CGImage],rect);

UIImage* elementImage=[UIImage imageWithCGImage:imageRef];

UIImageView*_imageView=[[UIImageView alloc] initWithImage:elementImage];

_imageView.frame=rect;

NSString*_imageString=[NSString stringWithFormat:@"%@_%d_%d.jpg",prefixName,i,j];

[_mutableDictionary setObject:_imageView forKey:_imageString];

//CFRelease(imageRef);

if (quality<=0

{

continue;

}

quality=(quality>1)?1:quality;

NSString*_imagePath=[NSHomeDirectory() stringByAppendingPathComponent:_imageString];

NSData* _imageData=UIImageJPEGRepresentation(elementImage, quality);

[_imageData writeToFile:_imagePath atomically:NO];

}

}

//return dictionary including image views

NSDictionary*_dictionary=_mutableDictionary;

return _dictionary;

}

转载于:https://www.cnblogs.com/zhulin/archive/2011/06/15/2082205.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值