前言:
壓縮圖片其實(shí)不是一個動作,而是兩個:“壓”和“縮”
壓:損失圖片的質(zhì)量,直觀的感覺就是清晰度下降
縮:縮小圖片的尺寸,直接的感覺就是圖片變小了
iOS 相關(guān)
UIImage 與 NSData 相互轉(zhuǎn)化
//UIImage to NSData
//此方法即為“壓”圖片,降低圖片質(zhì)量
var newImgData = UIImageJPEGRepresentation(image, 0.1)!
var newImgData = UIImagePNGRepresentation(image)
//NSData to UIImage
var newImg = UIImage.init(data: newImgData)!
重新繪制圖片
/*這是一個畫圖操作*/
//創(chuàng)建畫板,傳入畫板大小
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 相關(guān)
/*傳入一個圖片,壓縮后,存儲到用戶目錄的.unas/TemporayFiles/avatar-pending.jpg路徑下
*sourceImage:原圖
*/
- (void)compressWithImage:(NSImage *)sourceImage{
//NSImage 轉(zhuǎn) 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
//開始圖片質(zhì)量的壓,此代碼參考: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];
}