SDWebImage源碼解讀_之SDWebImageDecoder


第四篇

前言

首先,我們要弄明白一個問題? 為什么要對UIImage進行解碼呢?難道不能直接使用嗎?

其實不解碼也是可以使用的,假如說我們通過imageNamed:來加載image,系統默認會在主線程立即進行圖片的解碼工作。這一過程就是把image解碼成可供控件直接使用的位圖

當在主線程調用了大量的imageNamed:方法后,就會產生卡頓了。為了解決這個問題我們有兩種比較簡單的處理方法:

  1. 我們不使用imageNamed:加載圖片,使用其他的方法,比如imageWithContentsOfFile:
  2. 我們自己解碼圖片,可以把這個解碼過程放到子線程

通過上邊這兩點小小的建議,我們知道了處理圖片的一些小技巧。我們還需要知道圖片的一些基礎知識和如何解碼圖片。

圖像存儲

首先圖像的存儲是二維的,所以我們需要考慮如何表示圖像中某個特定位置的值。然后,我們需要考慮具體的值應該如何量化。另外,根據我們捕捉圖像的途徑,也會有不同的方式來編碼圖形數據。一般來說,最直觀的方式是將其存為位圖數據,可如果你想處理一組幾何圖形,效率就會偏低。一個圓形可以只由三個值 (兩個坐標值和半徑) 來表示,使用位圖會使文件更大,卻只能做粗略的近似。

不同於位圖把值存在陣列中,矢量格式存儲的是繪圖圖像的指令。在處理一些可以被歸納為幾何形狀的簡單圖像時,這樣做顯然更有效率;但面對照片數據時矢量儲存就會顯得乏力了。建築師設計房屋更傾向於使用矢量的方式,因為矢量格式並不僅僅局限於線條的繪制,也可以用漸變或圖案的填充作為展示,所以利用矢量方式完全可以生成房屋的擬真渲染圖。

用於填充的圖案單元則更適合被儲存為一個位圖,在這種情況下,我們可能需要一個混合格式。一個非常普遍的混合格式的一個例子是 PostScript,(或者時下比較流行的衍生格式,PDF),它基本上是一個用於繪制圖像的描述語言。上述格式主要針對印刷業,而 NeXT 和 Adobe 開發的 Display Postscript 則是進行屏幕繪制的指令集。PostScript 能夠排布字母,甚至位圖,這使得它成為了一個非常靈活的格式。

矢量圖像

矢量格式的一大優點是縮放。矢量格式的圖像其實是一組繪圖指令,這些指令通常是獨立於尺寸的。如果你想擴大一個圓形,只需在繪制前擴大它的半徑就可以了。位圖則沒這么容易。最起碼,如果擴大的比例不是二的倍數,就會涉及到重繪圖像,並且各個元素都只是簡單地增加尺寸,成為一個色塊。由於我們不知道這圖像是一個圓形,所以無法確保弧線的准確描繪,效果看起來肯定不如按比例繪制的線條那樣好。也因此,在像素密度不同的設備中,矢量圖像作為圖形資源會非常有用。位圖的話,同樣的圖標,在視網膜屏幕之前的 iPhone 上看起來並沒有問題,在拉伸兩倍后的視網膜屏幕上看起來就會發虛。就好像僅適配了 iPhone 的 App 運行在 iPad 的 2x 模式下就不再那么清晰了。

雖然 Xcode 6 已經支持了 PDF 格式,但迄今仍不完善,只是在編譯時將其創建成了位圖圖像。最常見的矢量圖像格式為 SVG,在 iOS 中也有一個渲染 SVG 文件的庫,SVGKit。

位圖

大部分圖像都是以位圖方式處理的,從這里開始,我們就將重點放在如何處理它們上。第一個問題,是如何表示兩個維度。所有的格式都以一系列連續的行作為單元,而每一行則水平地按順序存儲了每個像素。大多數格式會按照行的順序進行存儲,但是這並不絕對,比如常見的交叉格式,就不嚴格按照行順序。其優點是當圖像被部分加載時,可以更好的顯示預覽圖像。在互聯網初期,這是一個問題,隨着數據的傳輸速度提升,現在已經不再被當做重點。

表示位圖最簡單的方法是將二進制作為每個像素的值:一個像素只有開、關兩種狀態,我們可以在一個字節中存儲八個像素,效率非常高。不過,由於每一位只有最多兩個值,我們只能儲存兩種顏色。考慮到現實中的顏色數以百萬計,上述方法聽起來並不是很有用。不過有一種情況還是需要用到這樣的方法:遮罩。比如,圖像的遮罩可以被用於透明性,在 iOS 中,遮罩被應用在 tab bar 的圖標上 (即便實際圖標不是單像素位圖)。

如果要添加更多的顏色,有兩個基本的選擇:使用一個查找表,或直接用真實的顏色值。GIF 圖像有一個顏色表 (或色彩面板),可以存儲最多 256 種顏色。存儲在位圖中的值是該查詢列表中的索引值,對應着其相應的顏色。所以,GIF 文件僅限於 256 色。對於簡單的線條圖或純色圖,這是一種不錯的解決方法。但對於照片來說,就會顯示的不夠真實,照片需要更精細的顏色深度。進一步的改進是 PNG 文件,這種格式可以使用一個預置的色板或者獨立的通道,它們都支持可變的顏色深度。在一個通道中,每個像素的顏色分量 (紅,綠,藍,即 RGB,有時添加透明度值,即RGBA) 是直接指定的。

GIF 和 PNG 對於具有大面積相同顏色的圖像是最好的選擇,因為它們使用的 (主要是基於游程長度編碼的) 壓縮算法可以減少存儲需求。這種壓縮是無損的,這意味着圖像質量不會被壓縮過程影響。

一個有損壓縮圖像格式的例子是 JPEG。創建 JPEG 圖像時,通常會指定一個與圖像質量相關的壓縮比值參數,壓縮程度過高會導致圖像質量惡化。JPEG 不適用於對比鮮明的圖像 (如線條圖),其壓縮方式對類似區域的圖像質量損害會相對嚴重。如果某張截圖中包含了文本,且保存為 JPEG 格式,就可以清楚地看到:生成的圖像中字符周圍會出現雜散的像素點。在大部分照片中不存在這個問題,所以照片主要使用 JPEG 格式。

總結:就放大縮小而言,矢量格式 (如 SVG) 是最好的。對比鮮明且顏色數量有限的線條圖最適合 GIF 或 PNG (其中 PNG 更為強大),而照片,則應該使用 JPEG。當然,這些都不是不可逾越的規則,不過通常而言,對一定的圖像質量與圖像尺寸而言,遵守規則會得到最好的結果。

以上內容的來源

做一些好玩的事

連接了上邊的知識呢,就可以做一些好玩的事了。比如說給圖像打馬賽克,合並圖像等等。再次就不介紹怎么實現了。有興趣的同學可以自己網上去搜,例子很多。

+ (nullable UIImage *)decodedImageWithImage:(nullable UIImage *)image

好了,言歸正傳,讀完上邊的內容,我們明白了為什么要解碼圖片,那么這個方法就是解碼圖片的實現過程。這給我們提供了一種思路:我們有時在優化代碼的時候,可以考慮用這個方法來處理圖像數據。

static const size_t kBytesPerPixel = 4;
static const size_t kBitsPerComponent = 8;

+ (nullable UIImage *)decodedImageWithImage:(nullable UIImage *)image {
    if (![UIImage shouldDecodeImage:image]) {
        return image;
    }
   
    // autorelease the bitmap context and all vars to help system to free memory when there are memory warning.
    // on iOS7, do not forget to call [[SDImageCache sharedImageCache] clearMemory];
    @autoreleasepool{
        
        CGImageRef imageRef = image.CGImage;
        CGColorSpaceRef colorspaceRef = [UIImage colorSpaceForImageRef:imageRef];
        
        size_t width = CGImageGetWidth(imageRef);
        size_t height = CGImageGetHeight(imageRef);
        size_t bytesPerRow = kBytesPerPixel * width;

        // kCGImageAlphaNone is not supported in CGBitmapContextCreate.
        // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast
        // to create bitmap graphics contexts without alpha info.
        CGContextRef context = CGBitmapContextCreate(NULL,
                                                     width,
                                                     height,
                                                     kBitsPerComponent,
                                                     bytesPerRow,
                                                     colorspaceRef,
                                                     kCGBitmapByteOrderDefault|kCGImageAlphaNoneSkipLast);
        if (context == NULL) {
            return image;
        }
        
        // Draw the image into the context and retrieve the new bitmap image without alpha
        CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
        CGImageRef imageRefWithoutAlpha = CGBitmapContextCreateImage(context);
        UIImage *imageWithoutAlpha = [UIImage imageWithCGImage:imageRefWithoutAlpha
                                                         scale:image.scale
                                                   orientation:image.imageOrientation];
        
        CGContextRelease(context);
        CGImageRelease(imageRefWithoutAlpha);
        
        return imageWithoutAlpha;
    }
}

我們一行一行的看:

static const size_t kBytesPerPixel = 4;

kBytesPerPixel用來說明每個像素占用內存多少個字節,在這里是占用4個字節。(圖像在iOS設備上是以像素為單位顯示的)。

static const size_t kBitsPerComponent = 8;

kBitsPerComponent表示每一個組件占多少位。這個不太好理解,我們先舉個例子,比方說RGBA,其中R(紅色)G(綠色)B(藍色)A(透明度)是4個組件,每個像素由這4個組件組成,那么我們就用8位來表示着每一個組件,所以這個RGBA就是8*4 = 32位。

知道了kBitsPerComponent和每個像素有多少組件組成就能計算kBytesPerPixel了。計算公式是:(bitsPerComponent * number of components + 7)/8.

判斷要不要解碼

if (![UIImage shouldDecodeImage:image]) {
        return image;
    }

並不是所有的image都要解碼的。我們來看看shouldDecodeImage:這個函數:

+ (BOOL)shouldDecodeImage:(nullable UIImage *)image {
    // Prevent "CGBitmapContextCreateImage: invalid context 0x0" error
    if (image == nil) {
        return NO;
    }

    // do not decode animated images
    if (image.images != nil) {
        return NO;
    }
    
    CGImageRef imageRef = image.CGImage;
    
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(imageRef);
    BOOL anyAlpha = (alpha == kCGImageAlphaFirst ||
                     alpha == kCGImageAlphaLast ||
                     alpha == kCGImageAlphaPremultipliedFirst ||
                     alpha == kCGImageAlphaPremultipliedLast);
    // do not decode images with alpha
    if (anyAlpha) {
        return NO;
    }
    
    return YES;
}

不適合解碼的條件為:

  • image為nil
  • animated images 動圖不適合
  • 帶有透明因素的圖像不適合

獲取核心數據

通過CGImageRef imageRef = image.CGImage可以拿到和圖像有關的各種參數。

  • 顏色空間 CGColorSpaceRef colorspaceRef = [UIImage colorSpaceForImageRef:imageRef];
  • size_t width = CGImageGetWidth(imageRef);
  • size_t height = CGImageGetHeight(imageRef);
  • 計算出每行的像素數 size_t bytesPerRow = kBytesPerPixel * width;

創建沒有透明因素的bitmap graphics contexts

// kCGImageAlphaNone is not supported in CGBitmapContextCreate.
// Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast
// to create bitmap graphics contexts without alpha info.
CGContextRef context = CGBitmapContextCreate(NULL,
                                             width,
                                             height,
                                             kBitsPerComponent,
                                             bytesPerRow,
                                             colorspaceRef,
                                             kCGBitmapByteOrderDefault|kCGImageAlphaNoneSkipLast);
if (context == NULL) {
    return image;
}

注意:這里創建的contexts是沒有透明因素的。在UI渲染的時候,實際上是把多個圖層按像素疊加計算的過程,需要對每一個像素進行 RGBA 的疊加計算。當某個 layer 的是不透明的,也就是 opaque 為 YES 時,GPU 可以直接忽略掉其下方的圖層,這就減少了很多工作量。這也是調用 CGBitmapContextCreate 時 bitmapInfo 參數設置為忽略掉 alpha 通道的原因。

繪制圖像

// Draw the image into the context and retrieve the new bitmap image without alpha
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGImageRef imageRefWithoutAlpha = CGBitmapContextCreateImage(context);
UIImage *imageWithoutAlpha = [UIImage imageWithCGImage:imageRefWithoutAlpha
                                                 scale:image.scale
                                           orientation:image.imageOrientation];

CGContextRelease(context);
CGImageRelease(imageRefWithoutAlpha);

+ (nullable UIImage *)decodedAndScaledDownImageWithImage:(nullable UIImage *)image

/*
 * Defines the maximum size in MB of the decoded image when the flag `SDWebImageScaleDownLargeImages` is set
 * Suggested value for iPad1 and iPhone 3GS: 60.
 * Suggested value for iPad2 and iPhone 4: 120.
 * Suggested value for iPhone 3G and iPod 2 and earlier devices: 30.
 */
static const CGFloat kDestImageSizeMB = 60.0f;

/*
 * Defines the maximum size in MB of a tile used to decode image when the flag `SDWebImageScaleDownLargeImages` is set
 * Suggested value for iPad1 and iPhone 3GS: 20.
 * Suggested value for iPad2 and iPhone 4: 40.
 * Suggested value for iPhone 3G and iPod 2 and earlier devices: 10.
 */
static const CGFloat kSourceImageTileSizeMB = 20.0f;

static const CGFloat kBytesPerMB = 1024.0f * 1024.0f;
static const CGFloat kPixelsPerMB = kBytesPerMB / kBytesPerPixel;
static const CGFloat kDestTotalPixels = kDestImageSizeMB * kPixelsPerMB;
static const CGFloat kTileTotalPixels = kSourceImageTileSizeMB * kPixelsPerMB;

static const CGFloat kDestSeemOverlap = 2.0f;   // the numbers of pixels to overlap the seems where tiles meet.

+ (nullable UIImage *)decodedAndScaledDownImageWithImage:(nullable UIImage *)image {
    if (![UIImage shouldDecodeImage:image]) {
        return image;
    }
    
    if (![UIImage shouldScaleDownImage:image]) {
        return [UIImage decodedImageWithImage:image];
    }
    
    CGContextRef destContext;
    
    // autorelease the bitmap context and all vars to help system to free memory when there are memory warning.
    // on iOS7, do not forget to call [[SDImageCache sharedImageCache] clearMemory];
    @autoreleasepool {
        CGImageRef sourceImageRef = image.CGImage;
        
        CGSize sourceResolution = CGSizeZero;
        sourceResolution.width = CGImageGetWidth(sourceImageRef);
        sourceResolution.height = CGImageGetHeight(sourceImageRef);
        float sourceTotalPixels = sourceResolution.width * sourceResolution.height;
        // Determine the scale ratio to apply to the input image
        // that results in an output image of the defined size.
        // see kDestImageSizeMB, and how it relates to destTotalPixels.
        float imageScale = kDestTotalPixels / sourceTotalPixels;
        CGSize destResolution = CGSizeZero;
        destResolution.width = (int)(sourceResolution.width*imageScale);
        destResolution.height = (int)(sourceResolution.height*imageScale);
        
        // current color space
        CGColorSpaceRef colorspaceRef = [UIImage colorSpaceForImageRef:sourceImageRef];
        
        size_t bytesPerRow = kBytesPerPixel * destResolution.width;
        
        // Allocate enough pixel data to hold the output image.
        void* destBitmapData = malloc( bytesPerRow * destResolution.height );
        if (destBitmapData == NULL) {
            return image;
        }
        
        // kCGImageAlphaNone is not supported in CGBitmapContextCreate.
        // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast
        // to create bitmap graphics contexts without alpha info.
        destContext = CGBitmapContextCreate(destBitmapData,
                                            destResolution.width,
                                            destResolution.height,
                                            kBitsPerComponent,
                                            bytesPerRow,
                                            colorspaceRef,
                                            kCGBitmapByteOrderDefault|kCGImageAlphaNoneSkipLast);
        
        if (destContext == NULL) {
            free(destBitmapData);
            return image;
        }
        CGContextSetInterpolationQuality(destContext, kCGInterpolationHigh);
        
        // Now define the size of the rectangle to be used for the
        // incremental blits from the input image to the output image.
        // we use a source tile width equal to the width of the source
        // image due to the way that iOS retrieves image data from disk.
        // iOS must decode an image from disk in full width 'bands', even
        // if current graphics context is clipped to a subrect within that
        // band. Therefore we fully utilize all of the pixel data that results
        // from a decoding opertion by achnoring our tile size to the full
        // width of the input image.
        CGRect sourceTile = CGRectZero;
        sourceTile.size.width = sourceResolution.width;
        // The source tile height is dynamic. Since we specified the size
        // of the source tile in MB, see how many rows of pixels high it
        // can be given the input image width.
        sourceTile.size.height = (int)(kTileTotalPixels / sourceTile.size.width );
        sourceTile.origin.x = 0.0f;
        // The output tile is the same proportions as the input tile, but
        // scaled to image scale.
        CGRect destTile;
        destTile.size.width = destResolution.width;
        destTile.size.height = sourceTile.size.height * imageScale;
        destTile.origin.x = 0.0f;
        // The source seem overlap is proportionate to the destination seem overlap.
        // this is the amount of pixels to overlap each tile as we assemble the ouput image.
        float sourceSeemOverlap = (int)((kDestSeemOverlap/destResolution.height)*sourceResolution.height);
        CGImageRef sourceTileImageRef;
        // calculate the number of read/write operations required to assemble the
        // output image.
        int iterations = (int)( sourceResolution.height / sourceTile.size.height );
        // If tile height doesn't divide the image height evenly, add another iteration
        // to account for the remaining pixels.
        int remainder = (int)sourceResolution.height % (int)sourceTile.size.height;
        if(remainder) {
            iterations++;
        }
        // Add seem overlaps to the tiles, but save the original tile height for y coordinate calculations.
        float sourceTileHeightMinusOverlap = sourceTile.size.height;
        sourceTile.size.height += sourceSeemOverlap;
        destTile.size.height += kDestSeemOverlap;
        for( int y = 0; y < iterations; ++y ) {
            @autoreleasepool {
                sourceTile.origin.y = y * sourceTileHeightMinusOverlap + sourceSeemOverlap;
                destTile.origin.y = destResolution.height - (( y + 1 ) * sourceTileHeightMinusOverlap * imageScale + kDestSeemOverlap);
                sourceTileImageRef = CGImageCreateWithImageInRect( sourceImageRef, sourceTile );
                if( y == iterations - 1 && remainder ) {
                    float dify = destTile.size.height;
                    destTile.size.height = CGImageGetHeight( sourceTileImageRef ) * imageScale;
                    dify -= destTile.size.height;
                    destTile.origin.y += dify;
                }
                CGContextDrawImage( destContext, destTile, sourceTileImageRef );
                CGImageRelease( sourceTileImageRef );
            }
        }
        
        CGImageRef destImageRef = CGBitmapContextCreateImage(destContext);
        CGContextRelease(destContext);
        if (destImageRef == NULL) {
            return image;
        }
        UIImage *destImage = [UIImage imageWithCGImage:destImageRef scale:image.scale orientation:image.imageOrientation];
        CGImageRelease(destImageRef);
        if (destImage == nil) {
            return image;
        }
        return destImage;
    }
}

......... 這個方法也真夠長的,看了就頭疼啊。不過我們還是會一點點分析。我們能夠學會如何壓縮一個圖像。

最大支持壓縮圖像源的大小

static const CGFloat kDestImageSizeMB = 60.0f;

默認的單位是MB,這里設置了60MB。當我們要壓縮一張圖像的時候,首先就是要定義最大支持的源文件的大小,不能沒有任何限制。下邊是SDWebImage的建議:

/*
 * Defines the maximum size in MB of the decoded image when the flag `SDWebImageScaleDownLargeImages` is set
 * Suggested value for iPad1 and iPhone 3GS: 60.
 * Suggested value for iPad2 and iPhone 4: 120.
 * Suggested value for iPhone 3G and iPod 2 and earlier devices: 30.
 */

原圖方塊的大小

static const CGFloat kSourceImageTileSizeMB = 20.0f;

這個方塊將會被用來分割原圖,默認設置為20M。

1M有多少字節

static const CGFloat kBytesPerMB = 1024.0f * 1024.0f;

1M有多少像素

static const CGFloat kPixelsPerMB = kBytesPerMB / kBytesPerPixel;

目標總像素

static const CGFloat kDestTotalPixels = kDestImageSizeMB * kPixelsPerMB;

原圖放款總像素

static const CGFloat kTileTotalPixels = kSourceImageTileSizeMB * kPixelsPerMB;

重疊像素大小

static const CGFloat kDestSeemOverlap = 2.0f;   // the numbers of pixels to overlap the seems where tiles meet. 

重點來了,如何把一個很大的原圖壓縮成指定的大小?

原理: 首先定義一個大小固定的方塊,然后把原圖按照方塊的大小進行分割,最后把每個方塊中的數據畫到目標畫布上,這樣就能得到目標圖像了。接下來我們做出相信的解釋。

  1. 檢測圖像能否解碼

     if (![UIImage shouldDecodeImage:image]) {
             return image;
         }
    
  2. 檢查圖像應不應該壓縮,原則是:如果圖像大於目標尺寸才需要壓縮

     if (![UIImage shouldScaleDownImage:image]) {
             return [UIImage decodedImageWithImage:image];
         }
       
     + (BOOL)shouldScaleDownImage:(nonnull UIImage *)image {
         BOOL shouldScaleDown = YES;
             
         CGImageRef sourceImageRef = image.CGImage;
         CGSize sourceResolution = CGSizeZero;
         sourceResolution.width = CGImageGetWidth(sourceImageRef);
         sourceResolution.height = CGImageGetHeight(sourceImageRef);
         float sourceTotalPixels = sourceResolution.width * sourceResolution.height;
         float imageScale = kDestTotalPixels / sourceTotalPixels;
         if (imageScale < 1) {
             shouldScaleDown = YES;
         } else {
             shouldScaleDown = NO;
         }
         
         return shouldScaleDown;
     }
    
  3. 拿到數據信息 sourceImageRef

     CGImageRef sourceImageRef = image.CGImage;
    
  4. 計算原圖的像素 sourceResolution

     CGSize sourceResolution = CGSizeZero;
     sourceResolution.width = CGImageGetWidth(sourceImageRef);
     sourceResolution.height = CGImageGetHeight(sourceImageRef);
    
  5. 計算原圖總像素 sourceTotalPixels

     float sourceTotalPixels = sourceResolution.width * sourceResolution.height;
    
  6. 計算壓縮比例 imageScale

     // Determine the scale ratio to apply to the input image
     // that results in an output image of the defined size.
     // see kDestImageSizeMB, and how it relates to destTotalPixels.
     float imageScale = kDestTotalPixels / sourceTotalPixels;
    
  7. 計算目標像素 destResolution

     CGSize destResolution = CGSizeZero;
     destResolution.width = (int)(sourceResolution.width*imageScale);
     destResolution.height = (int)(sourceResolution.height*imageScale);
    
  8. 獲取當前的顏色空間 colorspaceRef

     // current color space
     CGColorSpaceRef colorspaceRef = [UIImage colorSpaceForImageRef:sourceImageRef];
    
     + (CGColorSpaceRef)colorSpaceForImageRef:(CGImageRef)imageRef {
         // current
         CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(CGImageGetColorSpace(imageRef));
         CGColorSpaceRef colorspaceRef = CGImageGetColorSpace(imageRef);
         
         BOOL unsupportedColorSpace = (imageColorSpaceModel == kCGColorSpaceModelUnknown ||
                                       imageColorSpaceModel == kCGColorSpaceModelMonochrome ||
                                       imageColorSpaceModel == kCGColorSpaceModelCMYK ||
                                       imageColorSpaceModel == kCGColorSpaceModelIndexed);
         if (unsupportedColorSpace) {
             colorspaceRef = CGColorSpaceCreateDeviceRGB();
             CFAutorelease(colorspaceRef);
         }
         return colorspaceRef;
     }
    
  9. 計算並創建目標圖像的內存 destBitmapData

     size_t bytesPerRow = kBytesPerPixel * destResolution.width;
     
     // Allocate enough pixel data to hold the output image.
     void* destBitmapData = malloc( bytesPerRow * destResolution.height );
     if (destBitmapData == NULL) {
         return image;
     }
    
  10. 創建目標上下文 destContext

    // kCGImageAlphaNone is not supported in CGBitmapContextCreate.
    // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast
    // to create bitmap graphics contexts without alpha info.
    destContext = CGBitmapContextCreate(destBitmapData,
                                        destResolution.width,
                                        destResolution.height,
                                        kBitsPerComponent,
                                        bytesPerRow,
                                        colorspaceRef,
                                        kCGBitmapByteOrderDefault|kCGImageAlphaNoneSkipLast);
    
    if (destContext == NULL) {
        free(destBitmapData);
        return image;
    }
    
  11. 設置壓縮質量

    CGContextSetInterpolationQuality(destContext, kCGInterpolationHigh);
    
  12. 計算第一個原圖方塊 sourceTile,這個方塊的寬度同原圖一樣,高度根據方塊容量計算

    // Now define the size of the rectangle to be used for the
    // incremental blits from the input image to the output image.
    // we use a source tile width equal to the width of the source
    // image due to the way that iOS retrieves image data from disk.
    // iOS must decode an image from disk in full width 'bands', even
    // if current graphics context is clipped to a subrect within that
    // band. Therefore we fully utilize all of the pixel data that results
    // from a decoding opertion by achnoring our tile size to the full
    // width of the input image.
    CGRect sourceTile = CGRectZero;
    sourceTile.size.width = sourceResolution.width;
    // The source tile height is dynamic. Since we specified the size
    // of the source tile in MB, see how many rows of pixels high it
    // can be given the input image width.
    sourceTile.size.height = (int)(kTileTotalPixels / sourceTile.size.width );
    sourceTile.origin.x = 0.0f;
    
  13. 計算目標圖像方塊 destTile

    // The output tile is the same proportions as the input tile, but
    // scaled to image scale.
    CGRect destTile;
    destTile.size.width = destResolution.width;
    destTile.size.height = sourceTile.size.height * imageScale;
    destTile.origin.x = 0.0f;
    
  14. 計算原圖像方塊與方塊重疊的像素大小 sourceSeemOverlap

    // The source seem overlap is proportionate to the destination seem overlap.
    // this is the amount of pixels to overlap each tile as we assemble the ouput image.
    float sourceSeemOverlap = (int)((kDestSeemOverlap/destResolution.height)*sourceResolution.height);
    
  15. 計算原圖像需要被分割成多少個方塊 iterations

    // calculate the number of read/write operations required to assemble the
    // output image.
    int iterations = (int)( sourceResolution.height / sourceTile.size.height );
    // If tile height doesn't divide the image height evenly, add another iteration
    // to account for the remaining pixels.
    int remainder = (int)sourceResolution.height % (int)sourceTile.size.height;
    if(remainder) {
        iterations++;
    }
    
  16. 根據重疊像素計算原圖方塊的大小后,獲取原圖中該方塊內的數據,把該數據寫入到相對應的目標方塊中

     // Add seem overlaps to the tiles, but save the original tile height for y coordinate calculations.
    float sourceTileHeightMinusOverlap = sourceTile.size.height;
    sourceTile.size.height += sourceSeemOverlap;
    destTile.size.height += kDestSeemOverlap;
    for( int y = 0; y < iterations; ++y ) {
        @autoreleasepool {
            sourceTile.origin.y = y * sourceTileHeightMinusOverlap + sourceSeemOverlap;
            destTile.origin.y = destResolution.height - (( y + 1 ) * sourceTileHeightMinusOverlap * imageScale + kDestSeemOverlap);
            sourceTileImageRef = CGImageCreateWithImageInRect( sourceImageRef, sourceTile );
            if( y == iterations - 1 && remainder ) {
                float dify = destTile.size.height;
                destTile.size.height = CGImageGetHeight( sourceTileImageRef ) * imageScale;
                dify -= destTile.size.height;
                destTile.origin.y += dify;
            }
            CGContextDrawImage( destContext, destTile, sourceTileImageRef );
            CGImageRelease( sourceTileImageRef );
        }
    }
    
  17. 返回目標圖像

    CGImageRef destImageRef = CGBitmapContextCreateImage(destContext);
    CGContextRelease(destContext);
    if (destImageRef == NULL) {
        return image;
    }
    UIImage *destImage = [UIImage imageWithCGImage:destImageRef scale:image.scale orientation:image.imageOrientation];
    CGImageRelease(destImageRef);
    if (destImage == nil) {
        return image;
    }
    

總結

好了,這篇文章已經很長了 ,但是令人高興的是,我們學到了很多關於圖像的知識。其中比較重要的是圖片的基礎知識,還有就是把圖片按照方塊進行切割的思想了,目前我能想的使用場景就是當我們加載一個比較大的數據時,可以把數據切成一個一個的方塊,然后顯示。

由於個人知識有限,如有錯誤之處,還望各路大俠給予指出啊

發現一片文章講解的也很有意思,一張圖片引發的深思

  1. SDWebImage源碼解讀 之 NSData+ImageContentType 簡書 博客園
  2. SDWebImage源碼解讀 之 UIImage+GIF 簡書 博客園
  3. SDWebImage源碼解讀 之 SDWebImageCompat 簡書 博客園


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM