圖片裁剪/縮略性能探究

最近搞圖片縮略,總結(jié)了幾種不同方式的。具體如下

UIKit

UIGraphicsBeginImageContext & drawInRect


- (UIImage*)scaleWithUIKit:(CGSize)size {
    TICK
    CGFloat width = self.size.width;
    CGFloat height = self.size.height;
    if (width * height ==0) {
        return self;
    }

    float verticalRadio  = size.height * 1.0 / height;
    float horizontalRadio = size.width * 1.0 / width;

    floatradio = 1;
    if (verticalRadio <1 || horizontalRadio <1) {
        radio = MIN(verticalRadio, horizontalRadio);
    }

    width = width * radio;
    height = height * radio;

    // 創(chuàng)建一個bitmap的context 并把它設(shè)置成為當前正在使用的context
    UIGraphicsBeginImageContext(CGSizeMake(width - 1, height - 1));
    // 繪制改變大小的圖片
    [self drawInRect:CGRectMake(0,0, width, height)];
    // 從當前context中創(chuàng)建一個改變大小后的圖片
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    // 使當前的context出堆棧
    UIGraphicsEndImageContext();
    TOCK
    // 返回新的改變大小后的圖片
    return scaledImage;
}

PS: 其中的TICK 和 TOCK 定義如下

#define TICK  CFAbsoluteTime before = CFAbsoluteTimeGetCurrent();
#define TOCK  NSLog(@"resize: %.2f ms", (CFAbsoluteTimeGetCurrent() - before) *1000);
// UIKit
NSString*path = [[NSBundlemainBundle]pathForResource:nameofType:exts];
UIImage*image = [UIImageimageWithContentsOfFile:path];
image = [imagescaleWithUIKit:UPLOAD_IMG_SIZE];

使用Time Profiler查看系統(tǒng)的調(diào)用過程,結(jié)果如下:

image

可以看出scaleImage方法中,[UIImage imageWithContentOfFile:]方法耗時11.00ms,scaleWithUIKit:方法耗時34.00ms,而[UIImage imageWithContentOfFile:]方法具體做了什么,可以參考我的另一篇文章圖片ImageI/O解碼探究

我們看下scaleWithUIKit:方法具體做了什么:

PNG的scaleWithUIKit

可以看出來,調(diào)用了PNGPlugin庫中的_cg_png_read_row方法,進行了圖片解碼。只不過,獲取圖片的過程在[UIImage imageWithContentOfFile:]方法中,進行了解壓縮。

JPEG的scaleWithUIKit

可以看出來,scaleWithUIKit方法中,調(diào)用了AppleJPEGPlugin庫中的FigPhotoJPEGDecodeJPEGIntoRGBSurface方法進行了解碼。

CoreGraphics

CGBitmapContextCreate & CGContextDrawImage & CGBitmapContextCreateImage


- (UIImage*)resizeCG:(CGSize)size {
    TICK
    if (!self) {
        return nil;
    }

    CGFloat width = self.size.width;
    CGFloat height = self.size.height;
    if (width * height == 0) {
        return self;
    }

    float verticalRadio  = size.height * 1.0 / height;
    float horizontalRadio = size.width * 1.0 / width;

    floatradio =1;
    if (verticalRadio <1 || horizontalRadio <1) {
        radio = MIN(verticalRadio, horizontalRadio);
    }

    width = width * radio;
    height = height * radio;

    CGImageRefimageRef = self.CGImage;
    size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef);
    size_t bytesPerRow = CGImageGetBytesPerRow(imageRef);
    CGColorSpaceRef colorSpaceRef = CGImageGetColorSpace(imageRef);
    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);

    CGContextRefcontext =CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpaceRef, bitmapInfo);
    if (!context) return nil;

    CGContextDrawImage(context,CGRectMake(0,0, width, height), imageRef);// decode
    CGImageRef newImageRef = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImageimageWithCGImage:newImageRef];

    CFRelease(context);
    CGImageRelease(newImageRef);
    TOCK
    return newImage;
}

調(diào)用過程如下:

PNG的resizeCG

其中的resizeCG耗時14.00ms,其中也進行了解碼。

JPEG的resizeCG

可以看出,resizeCG方法耗時28.00ms,其中也進行了解碼。(耗時過程有可能有誤差)

PS: 在iOS11.0~iOS11.4版本中,由于蘋果手機快捷鍵屏幕截屏生成的圖片中的bitmap信息產(chǎn)生了變化,導(dǎo)致上面的Core Graphics方法使用過程中報錯CGBitmapContextCreate: unsupported parameter combination,因此需要作出更改,具體報錯分析請移步至CGBitmapContextCreate: unsupported parameter combination問題調(diào)查及解決

ImageIO

CGImageSourceCreateThumbnailAtIndex


- (UIImage*)resizeWithData:(NSData*)data scaleSize:(CGSize)size {

    if (!data) {
        returnnil;
    }

    // Create the image source
    CGImageSourceRef imageSourceRef = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    if (!imageSourceRef) {
        return nil;
    }

    CGFloat maxPixelSize = MAX(size.width, size.height);
    // Create thumbnail options
    CFDictionaryRef options = (__bridge CFDictionaryRef) @{                                                       (__bridgeid)kCGImageSourceShouldCacheImmediately: (__bridgeid)kCFBooleanFalse,

                                                           (__bridgeid)kCGImageSourceShouldCache: (__bridgeid)kCFBooleanFalse,

                                                           (__bridgeid)kCGImageSourceCreateThumbnailFromImageAlways: (__bridgeid)kCFBooleanTrue,

                                                           (__bridgeid)kCGImageSourceThumbnailMaxPixelSize: [NSNumbernumberWithFloat:maxPixelSize]

                                                           };

    // Generate the thumbnail
    CGImageRefimageRef = CGImageSourceCreateThumbnailAtIndex(imageSourceRef, 0, options);

    UIImage*thumbnailImage = [UIImageimageWithCGImage:imageRef];

    CFRelease(imageSourceRef);
    CGImageRelease(imageRef);

    return thumbnailImage;
}

改方法是傳入的NSData對象,是未解壓的數(shù)據(jù),ImageI/O接受未解壓的數(shù)據(jù),進行decompress,然后再解碼進行圖片的縮略。針對ImageI/O的解碼,請移步至圖片ImageI/O解碼探究

CoreImage

  • (CIContext*)contextWithOptions: & createCGImage: fromRect:
- (UIImage *)resizeCI:(CGSize)size {

    if (!self) {
        return nil;
    }

    CGFloat width = self.size.width;
    CGFloat height = self.size.height;
    if (width * height ==0) {
        return self;
    }

    floatverticalRadio  = size.height * 1.0 / height;
    floathorizontalRadio = size.width * 1.0 / width;

    floatradio =1;
    if (verticalRadio < 1 || horizontalRadio < 1) {
        radio = MIN(verticalRadio, horizontalRadio);
    }

    CIImage *image = [CIImage imageWithCGImage:self.CGImage];
    CIFilter *filter = [CIFilter filterWithName:@"CILanczosScaleTransform"];
    [filter setValue:image forKey:kCIInputImageKey];
    [filter setValue:[NSNumber numberWithFloat:radio] forKey:kCIInputScaleKey];

    [filter setValue:[NSNumber numberWithFloat:1.0] forKey:kCIInputAspectRatioKey];

    CIImage *outputImage = [filtervalueForKey:kCIOutputImageKey];

    if (!outputImage) {
        returnnil;
    }

    CIContext *context = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer: @NO}];
    CGImageRefoutputImageRef = [contextcreateCGImage:outputImagefromRect:outputImage.extent];
    UIImage*newImage = [UIImageimageWithCGImage:outputImageRef];
    CGImageRelease(outputImageRef);

    return newImage;
}
PNG的resizeCI

可以看到改方法中調(diào)用了CoreImage中的CIMetalRenderToTextures,這句話是將緩沖區(qū)的數(shù)據(jù)渲染到紋理,整個過程是將圖片渲染到畫布的一環(huán),其中進行了解碼操作。

JPEG的resizeCI

同樣看到了JPEG格式的圖片,也進行了紋理渲染。

vImage


- (UIImage*)resizeVI:(CGSize)size {
    if (!self) {
        return nil;
    }

    CGFloat width = self.size.width;
    CGFloat height = self.size.height;

    floatverticalRadio  = size.height * 1.0 / self.size.height;
    floathorizontalRadio = size.width * 1.0 / self.size.width;

    floatradio =1;
    if (verticalRadio < 1 || horizontalRadio < 1) {
        radio = MIN(verticalRadio, horizontalRadio);
    }

    width = width * radio;
    height = height * radio;

    CGImageRef imageRef = self.CGImage;
    uint32_t bitsPerComponent = (uint32_t)CGImageGetBitsPerComponent(imageRef);
    uint32_t bitsPerPixel = (uint32_t)CGImageGetBitsPerPixel(imageRef);
    CGColorSpaceRef colorSpaceRef = CGImageGetColorSpace(imageRef);
    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
    vImage_CGImageFormat cgfromat = {
        .bitsPerComponent= bitsPerComponent,
        .bitsPerPixel = bitsPerPixel,
        .colorSpace = colorSpaceRef,
        .bitmapInfo = bitmapInfo,
        .version = 0,
        .decode = nil,
        .renderingIntent = kCGRenderingIntentDefault,
    };

    vImage_Buffer sourceBuffer = {};
    // 首先,創(chuàng)建一個buffer,可以用vImage提供的CGImage的便攜構(gòu)造方法,里面需要傳入原始數(shù)據(jù)所需要的format,這里就是ARGB8888
    vImage_Error a_ret = vImageBuffer_InitWithCGImage(&sourceBuffer, &cgfromat, NULL, imageRef, kvImageNoFlags);

    // 所有vImage的方法一般都有一個result,判斷是否成功
    if (a_ret != kvImageNoError) return NULL;

    // create a destination buffer
    vImage_Buffer destBuffer = {};

    CGFloatscale =self.scale;
    uint32_t bytesPerPixel = bitsPerPixel / 8;
    uint32_t destBytesPerRow = bytesPerPixel * width;

    destBuffer.width = width;
    destBuffer.height = height;
    destBuffer.rowBytes = destBytesPerRow;
    destBuffer.data = malloc(destBuffer.rowBytes* destBuffer.height);

    vImage_Error ret = vImageScale_ARGB8888(&sourceBuffer, &destBuffer, NULL, kvImageHighQualityResampling);
    if (ret != kvImageNoError) return NULL;

    CGImageRef outputImage = vImageCreateCGImageFromBuffer(&destBuffer, &cgfromat,NULL,NULL,kvImageNoFlags, &ret);
    if (ret != kvImageNoError) return NULL;

    UIImage *image = [[UIImage alloc] initWithCGImage:outputImage scale:scale orientation:self.imageOrientation];

    free(sourceBuffer.data);
    free(destBuffer.data);
    return image;
}

vImage對于大多人來說比較陌生,看下vImage的過程:

PNG的resizeVI

同樣是經(jīng)過了解碼過程。而且注意,vImage底層解碼也是使用的ImageI/O的方法。

JPEG的resizeVI

由此可見,vImage底層的解碼實現(xiàn)也是通過ImageI/O框架的方法。

當然,一些buffer的操作,以及vImageScale等操作是使用的vImage。其中涉及一些buffer的切換等操作。

以上五種方法,分別進行將512x384、1024x768、2048x1536三種尺寸的PNG和JPEG圖片縮略至256x192,統(tǒng)計了他們各自的耗時。

因為ImageI/O接受的入?yún)⑹荖SData對象,會經(jīng)過解壓縮并解碼縮略,為了實驗的公平性,其他四種入?yún)閁Iimage對象的方法,會將入?yún)Iimage的生成過程時間也算進去。這樣一來,統(tǒng)計了五種從path獲取到的圖片進行縮略的大致時間,統(tǒng)計如下:

PNG耗時統(tǒng)計
JPEG耗時統(tǒng)計

根據(jù)統(tǒng)計結(jié)果可以看出,CoreImage框架的方法性能相對較差,其中的CoreGraphics和ImageI/O相對比較突出些,由于實驗材料不夠充分,更大尺寸的圖片沒有測試,但是UIKit會隨著尺寸的增大,耗時會有較大的增加。同時,JPEG格式的圖片相對于PNG格式的圖片整體性能更好。

蘋果官方在Performance Best Practices section of the Core Image Programming Guide部分中特別推薦使用Core Graphics或Image I / O功能預(yù)先裁剪或縮小圖像。

那么基本確定了最好是使用CoreGraphics或者ImageI/O這兩種方案。但是,影響性能并不只是耗時,同時內(nèi)存的分配也是考量的重要方面。下面,針對CoreGraphics和ImageI/O,我們看一下兩者分配內(nèi)存的區(qū)別。

使用Instrments中的Allocations工具,查看內(nèi)存分配的情況。為了使實驗效果明顯,我們使用一張12000x12000尺寸的JPEG圖片,大小為20.9MB。我們的目標是將這張圖片縮略到長寬不能超過256。

CoreGraphics

縮略之前:

CoreGraphics縮略之前的內(nèi)存情況

請注意勾選的 VM:CG image 一欄,此時該欄總共分配了16.00KiB的內(nèi)存空間,此時依然留存16.00KiB的空間。(Total Bytes表示總共分配的內(nèi)存空間大小,Persistent Bytes表示目前沒有被回收的、依然使用的內(nèi)存空間)

下面進行縮略,縮略之后:

CoreGraphics縮略之后的內(nèi)存情況

VM:CG image 一欄在縮略之后,雖然最終的Persistent Bytes依然是16KiB,但是這個工程中Total Bytes為11.78MiB,也就是過程中臨時分配了11+MiB的空間,雖然最后多余的內(nèi)存都被回收了,但是證明了在縮略過程中的瞬時消耗內(nèi)存多大11+MiB。內(nèi)存的暴漲經(jīng)常會造成APP閃退。

之所以如此,是因為CGContextDrawImage時,先解碼圖片,再生成原始分辨率大小的bitmap,這個位圖大致相關(guān)于 圖片像素寬度 x 圖片像素高度 x 4。

ImageI/O

那么ImageI/O如何呢?我們來試驗下

縮略之前:

ImageI/O縮略之前的內(nèi)存情況

縮略之前跟CoreGraphics是一致的,在此不多贅述。

縮略之后:

ImageI/O縮略之后的內(nèi)存情況

VM:CG image 一欄在縮略之后,最終的Persistent Bytes依然是16KiB,Total Bytes為僅僅為320.00KiB,相對于使用CoreGraphics,ImageI/O在縮略過程中,不會生成對應(yīng)的bitmap,大大降低了瞬時峰值,而且圖片越大這種效果越明顯。

結(jié)論:

1、推薦使用CoreGraphics或者ImageI/O進行縮略操作

2、越大的圖片,更推薦使用ImageI/O,會大大降低瞬時內(nèi)存的峰值

參考文獻:

https://nshipster.com/image-resizing/

http://www.cocoachina.com/ios/20180305/22458.html

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

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