iOS 壓縮圖片

前言:

壓縮圖片其實(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];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容