前言:
压缩图片其实不是一个动作,而是两个:“压”和“缩”
压:损失图片的质量,直观的感觉就是清晰度下降
缩:缩小图片的尺寸,直接的感觉就是图片变小了
iOS 相关
UIImage 与 NSData 相互转化
//UIImage to NSData
//此方法即为“压”图片,降低图片质量
var newImgData = UIImageJPEGRepresentation(image, 0.1)!
var newImgData = UIImagePNGRepresentation(image)
//NSData to UIImage
var newImg = UIImage.init(data: newImgData)!
重新绘制图片
/*这是一个画图操作*/
//创建画板,传入画板大小
UIGraphicsBeginImageContext(CGSize.init(width: 120, height: 180))
//将图片绘制在画板上,newImg是一个UIImage对象
newImg.draw(in: CGRect.init(x: 0, y: 0, width: 120, height: 180))
newImg = UIGraphicsGetImageFromCurrentImageContext()!
拓展说明
1、图片的“压”是有所限度的,传入0.1、0.001、0.0001差别不大
2、UIImage有size属性
2、Data有count属性,通过这个属性能得到图片的大小
Mac 相关
/*传入一个图片,压缩后,存储到用户目录的.unas/TemporayFiles/avatar-pending.jpg路径下
*sourceImage:原图
*/
- (void)compressWithImage:(NSImage *)sourceImage{
//NSImage 转 NSData
NSData *imageData = [sourceImage TIFFRepresentation];
//判断图片大于 100kb 则压缩
if ([imageData length] > (100*1024)) {
//宽度固定为 100等比例缩放
NSRect targetFrame = NSMakeRect(0, 0, 100, 100*sourceImage.size.height/sourceImage.size.width);
//此 NSImage对象用于存储缩小后的图片
NSImage *targetImage;
NSImageRep *sourceImageRep = [sourceImage bestRepresentationForRect:targetFrame context:nil hints:nil];
targetImage = [[NSImage alloc] initWithSize:targetFrame.size];
[targetImage lockFocus];
[sourceImageRep drawInRect:targetFrame];
[targetImage unlockFocus];
//图片缩小完成,此代码参考:https://blog.csdn.net/flame_007/article/details/84837939
//开始图片质量的压,此代码参考:https://stackoverflow.com/questions/35249771/cocoa-image-compression-with-nsimage
NSData *imageDataOut = [targetImage TIFFRepresentation];
NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:imageDataOut];
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.5] forKey:NSImageCompressionFactor];
imageData = [rep representationUsingType:NSBitmapImageFileTypeJPEG properties:options];
}
//将图片存储到用户路径的.unas/TemporayFiles/avatar-pending.jpg目录下
NSString *localAvatar = [NSHomeDirectory() stringByAppendingPathComponent:@".unas/TemporayFiles/avatar-pending.jpg"];
[imageData writeToFile:localAvatar atomically:YES];
}