iOS ImageIO 的使用- CGImageSource圖像解碼

這里只講ImageIO中CGImageSource常見的三種使用方式,一種是進行圖片格式解碼讀取(包括原始圖片和生成縮略圖),另一種是獲取圖片的相關(guān)信息(如:定位,拍攝設(shè)備蛮原,分辨率等),最后一種是漸進式加載另绩。

基本知識

CGImageSource:解碼-讀取圖片數(shù)據(jù)類

    //查看支持解碼的type類型
    let mySourceTypes : CFArray = CGImageSourceCopyTypeIdentifiers();
    print(mySourceTypes);
    ps.支持格式過多儒陨,我刪了一部分日志
(
    "public.jpeg",
    "public.png",
    "com.compuserve.gif",
    "com.canon.tif-raw-image",
    "com.adobe.raw-image",
    "com.dxo.raw-image",
    "com.konicaminolta.raw-image",
    "com.olympus.sr-raw-image",
    "com.microsoft.ico",
    "com.microsoft.bmp",
    ...
    "com.apple.icns",
    "com.adobe.photoshop-image",
    "com.microsoft.cur",
    "com.truevision.tga-image",
    "com.ilm.openexr-image",
    "org.webmproject.webp",
    "public.radiance",
    "public.pbm",
    "public.mpo-image",
    "public.pvr",
    "com.microsoft.dds"
)

CGImageDestination:編碼-寫入數(shù)據(jù)類,寫入數(shù)據(jù)類放在另一篇文章中

     //查看支持編碼的type類型
     let myDestinationTypes : CFArray = CGImageDestinationCopyTypeIdentifiers();
     print(myDestinationTypes);

ImageSourceOption 鍵值

kCGImageSourceTypeIdentifierHint:設(shè)置預(yù)設(shè)的圖片格式板熊,格式參照UTType.h
kCGImageSourceShouldAllowFloat:如果文件格式支持框全,是否應(yīng)將圖像作為浮點CGImageRef返回
kCGImageSourceShouldCache:是否應(yīng)以解碼形式緩存圖像
kCGImageSourceCreateThumbnailFromImageIfAbsent:如果原圖中縮略圖不存在,是否根據(jù)原圖創(chuàng)建縮略圖
kCGImageSourceCreateThumbnailFromImageAlways:是否始終根據(jù)原圖創(chuàng)建縮略圖干签,即使原圖中存在縮略圖
kCGImageSourceThumbnailMaxPixelSize:縮略圖最大尺寸津辩,CFNumber格式
kCGImageSourceCreateThumbnailWithTransform:縮略圖是否根據(jù)原圖像的方向和像素縱橫比進行旋轉(zhuǎn)和縮放

一.導(dǎo)入圖片數(shù)據(jù),進行圖片格式解碼

正如前文基礎(chǔ)知識中CGImageSource支持解碼的圖片數(shù)據(jù)類型容劳,是不是除了png,jpg很多格式都沒見過喘沿。有一些格式圖片沒有辦法通過UIImage(named:String)來進行加載,這里就需要通過CGImageSource進行格式轉(zhuǎn)換成CGImage進行加載

    func createImageFromSource()-> CGImage?{
        let myOptions = [kCGImageSourceShouldCache : kCFBooleanTrue,kCGImageSourceShouldAllowFloat : kCFBooleanTrue] as CFDictionary;
        //這里我放了一張png圖片在工程中
        guard let imgPath = Bundle.main.path(forResource: "IMG_0868", ofType: ".PNG")else{
            return nil
        }
        guard let myImageSource = CGImageSourceCreateWithURL(URL(fileURLWithPath: imgPath) as CFURL, myOptions) else {
            print(stderr, "Image source is NULL.");
            return nil
        }
        //通過CGImageSourceCreateImageAtIndex函數(shù)生成cgimage格式數(shù)據(jù)
        guard let myImage = CGImageSourceCreateImageAtIndex(myImageSource,0,nil)else {
            print(stderr, "Image not created from image source.");
            return nil
        };
        return myImage;
    }

二.通過原圖獲取縮略圖

    func createThumbnailFromSource()-> CGImage?{
        let myOptions = [kCGImageSourceShouldCache : kCFBooleanTrue,kCGImageSourceShouldAllowFloat : kCFBooleanTrue] as CFDictionary;
        //這里我放了一張png圖片在工程中
        guard let imgPath = Bundle.main.path(forResource: "IMG_0868", ofType: ".PNG")else{
            return nil
        }
        guard let myImageSource = CGImageSourceCreateWithURL(URL(fileURLWithPath: imgPath) as CFURL, myOptions) else {
            print(stderr, "Image source is NULL.");
            return nil
        }
        let thumbnailOptions = [kCGImageSourceCreateThumbnailWithTransform : kCFBooleanTrue,kCGImageSourceCreateThumbnailFromImageIfAbsent : kCFBooleanTrue, kCGImageSourceThumbnailMaxPixelSize : 200] as CFDictionary;
        // 生成縮略圖
        guard let thumbnailImage = CGImageSourceCreateThumbnailAtIndex(myImageSource,0,thumbnailOptions)else {
            print(stderr, "Image not created from image source.");
            return nil
        };
     
        return thumbnailImage;
    }

三.獲取圖片的相關(guān)信息

圖片視頻等文件其實都是一個壓縮包竭贩,里面包含很多信息蚜印,通過指定的格式解壓才有了我們看到的效果。圖片中就包含定位留量、拍攝設(shè)備窄赋、拍攝日期以及大小等等。通過CGImageSourceCopyPropertiesAtIndex就可以拿到這些信息楼熄,具體需要用到什么信息再自行加工忆绰。CGImageProperties詳細對照表

    func getPropertiesFromImgSource() -> [String:Any]? {
        // Create the dictionary
        let myOptions : CFDictionary = [kCGImageSourceShouldCache : kCFBooleanTrue,kCGImageSourceShouldAllowFloat : kCFBooleanTrue] as CFDictionary;
        // Create an image source from the URL.
        guard let imgPath = Bundle.main.path(forResource: "IMG_0851", ofType: ".HEIC")else{
            return nil
        }
        guard let myImageSource = CGImageSourceCreateWithURL(URL(fileURLWithPath: imgPath) as CFURL, myOptions) else {
            print(stderr, "Image source is NULL.");
            return nil
        }
        
        guard let props : NSDictionary = CGImageSourceCopyPropertiesAtIndex(myImageSource, 0, nil)else{
                    return nil
            }
        print(props)
        //需要返回數(shù)據(jù)自行進行加工
        return nil
    }

打印內(nèi)容
{
    ColorModel = RGB;
    DPIHeight = 72;
    DPIWidth = 72;
    Depth = 8;
    Orientation = 1;
    PixelHeight = 3024;
    PixelWidth = 4032;
    PrimaryImage = 1;
    ProfileName = "Display P3";
    "{Exif}" =     {
        ...
    };
    "{GPS}" =     {
        ...
    };
    "{MakerApple}" =     {
      ...
    };
    "{TIFF}" =     {
      ...
    };
}

四.逐步加載圖片

在某些時候加載一張比較大的或者質(zhì)量比較高的圖片,下載時間比較長可岂。會影響用戶體驗错敢,通過CGImageSourceUpdateData逐步更新圖片數(shù)據(jù)就會使體驗變得更好一些。

    //用來接收請求返回的data
    var imgData = Data()
    //這里用本地網(wǎng)絡(luò)請求下載圖片缕粹,多張圖片加載時請使用多線程優(yōu)化稚茅,不做過多闡述
    func createCreFromSource(){
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
        let task = session.dataTask(with: URL(string: "http://localhost:8181/download?fileName=IMG_1438.JPG")!)
        task.resume()
    }
    //通過URLSessionDataDelegate實現(xiàn),不要用block平斩,block會在拿到所有數(shù)據(jù)后觸發(fā)
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
       //拼接接收到的data數(shù)據(jù)
       imgData.append(data)

       let imageOptions = [kCGImageSourceShouldCache : kCFBooleanTrue,kCGImageSourceShouldAllowFloat : kCFBooleanTrue] as CFDictionary
       let incrementSource = CGImageSourceCreateIncremental(nil)
       CGImageSourceUpdateData(incrementSource, self.imgData as CFData, dataTask.countOfBytesExpectedToReceive == self.imgData.count)
       let status = CGImageSourceGetStatus(incrementSource)
       switch status {
             case .statusComplete,.statusIncomplete:
               if let cgImage = CGImageSourceCreateImageAtIndex(incrementSource, 0, imageOptions){
                   DispatchQueue.main.async {
                    //用到orientation因為測試圖片旋轉(zhuǎn)了90度亚享,在查找原因
                    self.imgView.image = UIImage(cgImage: cgImage, scale: 1.0, orientation: UIImage.Orientation.right)
                   }
               }
             default:
                break
           }
    }
Apple官方文檔:文檔地址ImageIOGuide
ImageIO的使用之CGImageDestination圖像編碼
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市绘面,隨后出現(xiàn)的幾起案子虹蒋,更是在濱河造成了極大的恐慌糜芳,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件魄衅,死亡現(xiàn)場離奇詭異,居然都是意外死亡塘辅,警方通過查閱死者的電腦和手機晃虫,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來扣墩,“玉大人哲银,你說我怎么就攤上這事∩胩瑁” “怎么了荆责?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長亚脆。 經(jīng)常有香客問我做院,道長,這世上最難降的妖魔是什么濒持? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任键耕,我火速辦了婚禮,結(jié)果婚禮上柑营,老公的妹妹穿的比我還像新娘屈雄。我一直安慰自己,他們只是感情好官套,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布酒奶。 她就那樣靜靜地躺著,像睡著了一般奶赔。 火紅的嫁衣襯著肌膚如雪惋嚎。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天纺阔,我揣著相機與錄音瘸彤,去河邊找鬼。 笑死笛钝,一個胖子當(dāng)著我的面吹牛质况,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播玻靡,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼结榄,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了囤捻?” 一聲冷哼從身側(cè)響起臼朗,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后视哑,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體绣否,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年挡毅,在試婚紗的時候發(fā)現(xiàn)自己被綠了蒜撮。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡跪呈,死狀恐怖段磨,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情耗绿,我是刑警寧澤苹支,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站误阻,受9級特大地震影響债蜜,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜堕绩,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一策幼、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧奴紧,春花似錦特姐、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至沫浆,卻和暖如春捷枯,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背专执。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工淮捆, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人本股。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓攀痊,卻偏偏與公主長得像,于是被迫代替她去往敵國和親拄显。 傳聞我的和親對象是個殘疾皇子苟径,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容