在项目开发中,我们很多时候,需要在原有图片的基础上,将图片进行压缩。而大多数时候,我们都是在接口方直接获取的图片链接。而此篇,就是为了解决,将压缩网络图片,进而展示在UI上
首先,将接口获取的图片,转成NSData :
NSData *data = [NSDatadataWithContentsOfURL:[NSURLURLWithString:@"网络图片地址"]];
将data抓成UIImage:
UIImage *image = [UIImageimageWithData:data];
压缩图片操作:
参数image 当前需要压缩的图片
参数 size 需要压缩到的尺寸
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
UIImage *newimage;
if (nil == image)
{
newimage = nil;
}
else
{
CGSize oldsize = image.size;
CGRect rect;
if (asize.width/asize.height > oldsize.width/oldsize.height)
{
rect.size.width = size.height* oldsize.width/ oldsize.height;
rect.size.height = asize.height;
rect.origin.x = (asize.width - rect.size.width) / 2;
rect.origin.y =0;
}
else
{
rect.size.width = asize.width;
rect.size.height = size.width* oldsize.height/ oldsize.width;
rect.origin.x =0;
rect.origin.y = (asize.height - rect.size.height) / 2;
}
UIGraphicsBeginImageContext(asize);
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColorclearColor]CGColor]);
UIRectFill(CGRectMake(0,0, asize.width, asize.height));
[image drawInRect:rect];
newimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return newimage;
}
调用压缩图片:
UIImage *compress = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(200,200)];
到此为止,压缩网络图片操作完成。
注意:上述操作,要在子线程中进行,否则会卡主线程