变更记录
序号 | 录入时间 | 录入人 | 备注 |
---|---|---|---|
1 | 2016-01-22 | Alfred Jiang | - |
方案名称
UIImage - 获取 UIImage 大小与压缩 UIImage
关键字
UIImage \ 大小 \ 尺寸 \ 压缩
需求场景
- 需要对加载的 UIImage 进行压缩时
参考链接
详细内容
获取 UIImage 大小
UIImage *testImage = [UIImage imageNamed:@"blue2.png"]; //877KB 600*600像素
NSUInteger s1 = UIImagePNGRepresentation(testImage).length; //992400
NSUInteger s2 = UIImageJPEGRepresentation(testImage, 1).length; //923162
NSUInteger s3 = CGImageGetHeight(testImage.CGImage) * CGImageGetBytesPerRow(testImage.CGImage); //1440000 = 600 * 600 * 4
//像素尺寸
CGFloat fixelW = CGImageGetWidth(testImage.CGImage);
CGFloat fixelH = CGImageGetHeight(testImage.CGImage);
测试文件大小为 877KB 600*600像素
其中 s1 为保存 PNG 格式文件最大内存占用大小
其中 s2 为保存 JPEG 格式文件最大内存占用大小
其中 s3 为该图片文件当前实际内存占用大小,与像素有关
从测试数据可见实际使用图片所占用内存大小往往大于图片实际大小,所以建议对较大图片进行压缩使用
压缩 UIImage
UIImage+Scale.h
@interface UIImage (Scale)
//等比率缩放
- (UIImage *)scaleImageToScale:(float)scale;
//自定长宽
- (UIImage*)scaleImageToSize:(CGSize)size;
@end
UIImage+Scale.m
#import "UIImage+Scale.h"
@implementation UIImage (Scale)
//等比率缩放
- (UIImage *)scaleImageToScale:(float)scale
{
UIGraphicsBeginImageContext(CGSizeMake(self.size.width * scale, self.size.height * scale));
[self drawInRect:CGRectMake(0, 0, self.size.width * scale, self.size.height * scale)];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
//自定长宽
- (UIImage*)scaleImageToSize:(CGSize)size
{
UIGraphicsBeginImageContext(size);
[self drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
@end
使用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
UIImage *imagePhoto = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData * imageData_before = UIImageJPEGRepresentation(imagePhoto,1);
NSLog(@"Before : %d , %@",[imageData_before length]/1024,imagePhoto);
imagePhoto = [imagePhoto scaleImageToSize:CGSizeMake(600, 600)];
NSData * imageData_after = UIImageJPEGRepresentation(imagePhoto,1);
NSLog(@"After : %d , %@",[imageData_after length]/1024,imagePhoto);
}
输出:
Before : 1504 , <UIImage: 0x796561e0> size {2560, 1600} orientation 0 scale 1.000000
After : 341 , <UIImage: 0x78e4e2f0> size {600, 600} orientation 0 scale 1.000000
效果图
(无)
备注
(无)