拉伸图片的时候怎么才能让图片不变形?
UIImage *image = [[UIImage imageNamed:@"xxx"] stretchableImageWithLeftCapWidth:10 topCapHeight:10];
(刚才有人提醒这个已经deprecated了哈,现在的方法叫resizableImageWithCapInsets).
文/叶孤城___(简书作者)
原文链接:http://www.jianshu.com/p/08f194e9904c
有时在相册里面上传图片时,图片过大而不能显示,如果是上传小量图片用 苹果推荐的 :
UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality);
下面用一张 292kb 的图片上传出现如下结果:
- 没处理图片之前:
图片过大时,服务器返回:
-
压缩图片后,再上传:
建一个分类:@interface UIImageView (Album)
/** *
动态发布图片压缩
@param source_image 原图image
* @param maxSize
限定的图片大小
*
@return 返回处理后的图片 */
- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize;
-
实现方法:
/**
* 先调整分辨率,分辨率可以自己设定一个值,大于的就缩小到这分辨率,小余的就保持原本分辨率。然后在判断图片数据大小,传入范围maxSize = 100 ,大于的再压缩,小的就保持原样
*/
-(NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize {
//先调整分辨率
CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height); CGFloat tempHeight = newSize.height / 1024;
CGFloat tempWidth = newSize.width / 1024;if (tempWidth > 1.0 && tempWidth > tempHeight) { newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth); } else if (tempHeight > 1.0 && tempWidth < tempHeight){ newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight); } UIGraphicsBeginImageContext(newSize); [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //调整大小 NSData *imageData = UIImageJPEGRepresentation(newImage,1.0); NSUInteger sizeOrigin = [imageData length]; NSUInteger sizeOriginKB = sizeOrigin / 1024; // 判断是否大于传入的值 if (sizeOriginKB > maxSize) { NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.50); return finallImageData; } return imageData; }
在相册实现方法:
#pragma mark --- 经测试OK
NSData *data = [self.imageViewAlbum resetSizeOfImageData:self.img maxSize:1024];
self.imageViewAlbum.image = [self.imageViewAlbum.image initWithData:data];
// 上传头像
[self uploadHeadImageWithImage:self.imageViewAlbum.image];
// 隐藏相册
[picker dismissViewControllerAnimated:YES completion:nil];