您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

用 ImageIO 實作圖片漸進式加載,並讀取 EXIF 完整資訊

編輯:iOS 相關教學

一、漸進式加載的三種常見流派

所謂漸進式加載,指的是網路圖片還沒下載完就先呈現一個可看的樣子,而不是等使用者盯著空白。實務上大致有三種做法:

  1. 多尺寸遞進:先拉一張小縮圖拉伸顯示,接著抓中等尺寸覆蓋,最後載入原圖。畫面清晰度分三段落提升。
  2. 邊下边繪:直接抓原圖,每收到一塊資料就重繪一次,形成由上而下逐漸浮現的效果。
  3. 混合式:先用縮圖墊底,再以第二種方式拉原圖。兼顧了視覺體驗與請求次數。

第二、三種正是 ImageIO 擅長的場景。官方指南的原文是:

If you have a very large image, or are loading image data over the web, you may want to create an incremental image source so that you can draw the image data as you accumulate it.

換句話說,當圖片很大或來自網路時,建立一個 incremental image source,就能在資料累積的過程中隨時取出目前可渲染的畫面。

二、CGImageSource 的漸進式加載實作

做法不複雜:開一個 NSURLConnection,建立一個空的 CGImageSource,每次收到資料就更新它,再重新取一次圖。

#import "SvIncrementallyImage.h"
#import <ImageIO/ImageIO.h>
#import <CoreFoundation/CoreFoundation.h>

@interface SvIncrementallyImage () {
    NSURLRequest      *_request;
    NSURLConnection   *_conn;
    CGImageSourceRef   _incrementallyImgSource;
    NSMutableData     *_recieveData;
    long long          _expectedLeght;
    bool               _isLoadFinished;
}
@property (nonatomic, retain) UIImage *image;
@property (nonatomic, retain) UIImage *thumbImage;
@end

@implementation SvIncrementallyImage

- (id)initWithURL:(NSURL *)imageURL {
    self = [super init];
    if (self) {
        _imageURL = imageURL;
        _request  = [[NSURLRequest alloc] initWithURL:_imageURL];
        _conn     = [[NSURLConnection alloc] initWithRequest:_request delegate:self];

        // 關鍵:建立一個空的增量式 image source
        _incrementallyImgSource = CGImageSourceCreateIncremental(NULL);
        _recieveData   = [[NSMutableData alloc] init];
        _isLoadFinished = false;
    }
    return self;
}

#pragma mark - NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    _expectedLeght = response.expectedContentLength;

    // 非圖片直接取消,別浪費流量
    NSArray *arr = [response.MIMEType componentsSeparatedByString:@"/"];
    if (arr.count < 1 || ![[arr objectAtIndex:0] isEqual:@"image"]) {
        [connection cancel];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_recieveData appendData:data];
    _isLoadFinished = (_expectedLeght == _recieveData.length);

    CGImageSourceUpdateData(_incrementallyImgSource, (CFDataRef)_recieveData, _isLoadFinished);
    CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementallyImgSource, 0, NULL);
    self.image = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);   // Create 規則:記得放
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // 若收尾時仍有未更新的資料,補一次 final 更新
    if (!_isLoadFinished) {
        CGImageSourceUpdateData(_incrementallyImgSource, (CFDataRef)_recieveData, true);
        CGImageRef imageRef = CGImageSourceCreateImageAtIndex(_incrementallyImgSource, 0, NULL);
        self.image = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);
    }
}
@end

整個流程就三個動作:建立空的 image source、CGImageSourceUpdateData 餵資料、CGImageSourceCreateImageAtIndex 取圖。第三個參數 final 是否為 true,決定 ImageIO 要不要把這批資料當成收尾處理。

三、為什麼「少量資料就能畫出東西」

這不是魔法,而是圖片格式的結構使然。任何圖片檔都由「檔頭 metadata」與「實際像素資料」組成,而檔頭通常很小。以最單純的 BMP 為例:

  1. BITMAPFILEHEADER:記錄檔案大小,以及像素資料距檔頭的偏移量;
  2. BITMAPINFOHEADER:寬、高、位深等資訊;
  3. 可選的調色板;
  4. 最後才是像素資料本體。

前三段加起來通常不超過一百 bytes。也就是說,只要拿到開頭這一小塊,就已經足以建立一個尺寸正確的畫布;後續資料越完整,畫面細節就越清楚,直到全部到齊。JPEG 與 PNG 的結構更複雜,但「檔頭 + 資料本體」這個大框架是一致的。ImageIO 的價值,就在於替我們處理了各家格式的解碼細節。

順帶一提,早期在處理一張 10000×8000 的中國地圖時,整張圖載入記憶體會直接撐爆。這類超大圖的正解是分片(tiling):每次只解一小塊區域,而不是一次攤開全圖。

四、讀取 EXIF:藏在像素背後的資訊

一張照片除了看得到的像素,還有拍攝時間、光圈、快門、ISO、GPS 等大量 metadata。UIImage 把它們全藏了起來,只留 imageOrientation 給你;要看全部,得走 ImageIO。

ImageIO 屬於偏底層的框架,介面是 C 風格、資料結構來自 CoreFoundation。所幸 CoreFoundation 有 T bridging(toll-free bridging),能與 Foundation 的型別無縫互轉,操作起來並不難。

入口是 CGImageSourceRef:透過它能取得檔案的 UTI、包含幾張圖、逐張存取,以及每張圖的 EXIF。所謂「幾張圖」是因為 GIF 這類格式單一檔案內可能含數十幀,一般 JPEG/PNG 則 CGImageSourceGetCount 回傳 1。

以下是 iPhone 相機所拍照片的屬性輸出(節錄):

image property: {
    ColorModel = RGB;
    DPIHeight = 72;  DPIWidth = 72;  Depth = 8;
    Orientation = 6;
    PixelHeight = 2448;  PixelWidth = 3264;
    "{Exif}" = {
        ApertureValue  = "2.526069";
        ExposureTime   = "0.06666667";
        FNumber        = "2.4";
        FocalLength    = "4.13";
        ISOSpeedRatings = ( 400 );
        DateTimeOriginal = "2013:06:24 22:11:30";
        ...
    };
    "{GPS}" = {
        Latitude = "22.5645";  LatitudeRef = N;
        Longitude = "113.8886666666667";  LongitudeRef = E;
        Altitude = "27.77328";
    };
    "{TIFF}" = {
        Make = Apple;  Model = "iPhone 5";
        Software = "6.1.4";
    };
}

方向欄位是個陷阱

最開頭那幾項分別是顏色模式、位深、DPI、實際像素與方向。看到 Orientation 時很容易以為它就是 UIImage 的 imageOrientation,但兩者數值並不相等。EXIF 定義的方向是 1~8,順序與 UIKit 不同,對應關係如下:

enum {
    exifOrientationUp  = 1,   // UIImageOrientationUp
    exifOrientationDown  = 3, // UIImageOrientationDown
    exifOrientationLeft  = 6, // UIImageOrientationLeft
    exifOrientationRight = 8, // UIImageOrientationRight

    // 以下四種並非所有相機都會產生,但 iOS 支援
    exifOrientationUpMirrored    = 2,
    exifOrientationDownMirrored  = 4,
    exifOrientationLeftMirrored  = 5,
    exifOrientationRightMirrored = 7,
};
typedef NSInteger ExifOrientation;

市面上多數相機與手機只會寫入前四種;鏡像的幾種通常出現在前鏡頭自拍時。

那 EXIF 為什麼要多這一層?因為感光元件本身有固定方向,如果每拍一張就把像素實際旋轉一次,對每秒數張的連拍來說成本極高。更聰明的做法是:拍攝時只記下「這個方向」,顯示時再依指示旋轉。於是只要讀圖軟體願意遵守規則,就能兼顧成像速度與正確顯示。

大多數相簿與編輯軟體都遵守這個規則,但 Windows 內建的檢視器是個著名例外——它不讀方向欄位,所以手機拍的直式照片匯入電腦後經常是躺著的。

EXIF 裡還有 GPS 資訊(iOS 相簿的「地點」分頁就靠它)、以及許多更冷門的欄位,有興趣可以自己寫個小程式把整組 metadata 印出來研究。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved