关键就是压到微信需要的大小
直接贴代码
- (UIImage *)handleImageWithURLStr:(NSString *)imageURLStr {
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[kHTTP_HEAD stringByAppendingString:imageURLStr]]];
NSData *newImageData = imageData;
// 压缩图片data大小
newImageData = UIImageJPEGRepresentation([UIImage imageWithData:newImageData scale:0.1], 0.1f);
UIImage *image = [UIImage imageWithData:newImageData];
// 压缩图片分辨率(因为data压缩到一定程度后,如果图片分辨率不缩小的话还是不行)
CGSize newSize = CGSizeMake(200, 200);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,(NSInteger)newSize.width, (NSInteger)newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
2017.7.5更新——压缩图片至指定大小
首先压缩图片有两种方法,一种压缩图片文件大小,一种压缩图片尺寸,百度都能知道,就不多说了。
1、压缩文件大小方法如下,此方法不能循环使用,因为压缩到一定比例再调用该方法就无效了
// 压缩图片
- (UIImage *)scaleImageCompression:(UIImage *)image {
CGFloat origanSize = [self getImageLengthWithImage:image];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
if (origanSize > 1024) {
imageData=UIImageJPEGRepresentation(image, 0.1);
} else if (origanSize > 512) {
imageData=UIImageJPEGRepresentation(image, 0.5);
}
UIImage *image1 = [UIImage imageWithData:imageData];
return image1;
}
2、这里是压缩到指定尺寸的关键代码,maxSize是想要压缩到的尺寸,单位kb。
建议先使用方法一压缩之后,再采取方法二压缩
// 压缩图片尺寸
- (UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
// Create a graphics image context
NSInteger newWidth = (NSInteger)newSize.width;
NSInteger newHeight = (NSInteger)newSize.height;
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
// Tell the old image to draw in this new context, with the desired
// new size
[image drawInRect:CGRectMake(0 , 0,newWidth, newHeight)];
// Get the new image from the context
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
// End the context
UIGraphicsEndImageContext();
// Return the new image.
return newImage;
}
- (CGFloat)getImageLengthWithImage:(UIImage *)image {
NSData * imageData = UIImageJPEGRepresentation(image,1);
CGFloat length = [imageData length]/1000;
return length;
}