iOS ImageIO 的使用- CGImageDestination圖像編碼

這篇文章來介紹ImageIO中CGImageDestination的常見使用,CGImageDestination常見使用主要有兩種:

1.添加一張或多張圖片進(jìn)行格式的轉(zhuǎn)換并輸出,并且支持寫入元數(shù)據(jù),如何查看屬性請(qǐng)看CGImageSource的使用中的描述
2.制作動(dòng)圖,例如制作GIF圖

基本知識(shí)

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

    //查看支持解碼的type類型,日志需自行打印
    let mySourceTypes : CFArray = CGImageSourceCopyTypeIdentifiers();
    print(mySourceTypes);

CGImageDestination:編碼-寫入圖片數(shù)據(jù)類

     //查看支持編碼的type類型,日志需自行打印
     let myDestinationTypes : CFArray = CGImageDestinationCopyTypeIdentifiers();
     print(myDestinationTypes);

CGImageProperties:支持修改的屬性
屬性有很多類,常見的有GPS信息、拍攝設(shè)備信息、曝光度等等,這里附上Apple官方文檔鏈接詳細(xì)列表

一、圖片格式轉(zhuǎn)換,添加屬性并保存

如果你的項(xiàng)目要求圖像格式統(tǒng)一,而且是特定格式。這個(gè)時(shí)候你就需要用圖像重新便來達(dá)到目的。
如果你的項(xiàng)目產(chǎn)品經(jīng)理想允許用戶向圖像添加關(guān)鍵字或更改飽和度、曝光或其他值,則需要將這些信息保存在選項(xiàng)字典中。
CGImageDestination初始化方法有三種:
CGImageDestinationCreateWithDataConsumer():指定CGDataConsumer接收編碼數(shù)據(jù)來創(chuàng)建
CGImageDestinationCreateWithData():指定CFData接收編碼數(shù)據(jù)來創(chuàng)建,樣例中用的便是這種創(chuàng)建方式
CGImageDestinationCreateWithURL():指定保存文件路徑來創(chuàng)建,如果該文件路徑已存在內(nèi)容,則會(huì)被覆蓋

//重編碼的過程,會(huì)去掉圖像資源的一些額外信息(如:TIFF、Exif等),如果需要這些原始的額外信息請(qǐng)通過解碼獲取,然后再進(jìn)行編碼設(shè)置
    func setImgPropertiesWithDestination(){
        let image = UIImage(named: "IMG_0851.HEIC")
        guard let newData = CFDataCreateMutable(kCFAllocatorDefault, 0) else { return }

        //1.創(chuàng)建CGImageDestination,type是編碼后的格式("public.png"=kUTTypePNG,更支持使用UTType),count是添加image張數(shù),optional是預(yù)留的填nil就可以
        guard let imgDestinationSource = CGImageDestinationCreateWithData(newData, "public.png" as CFString, 1, nil) else {
            print(stderr, "Fail to create imgDestination");
            return
        }
        //properties的數(shù)據(jù),這里是通過ImageSource解碼得到復(fù)制過來的,用官方宏定義替換了兩個(gè)參數(shù)名kCGImagePropertyGPSDictionary、kCGImagePropertyGPSLatitudeRef
        var properties = [kCGImagePropertyGPSDictionary : ["Altitude" : "4341.225913621262",
                          "AltitudeRef" : 0,
                          "DestBearing" : "235.8580323785803",
                          "DestBearingRef" : "T",
                          "HPositioningError" : 5,
                          "ImgDirection" : "235.8580323785803",
                          "ImgDirectionRef" : "T",
                          "Latitude" : "30.423055",
                          kCGImagePropertyGPSLatitudeRef : "N" as CFString,
                          "Longitude" : "90.8759",
                          "LongitudeRef" : "E",
                          "Speed" : 0,
                          "SpeedRef" : "K"]] as CFDictionary
        //2.添加圖像,設(shè)置參數(shù)
        CGImageDestinationAddImage(imgDestinationSource, (image?.cgImage)!, properties)
        //3.CGImageDestinationFinalize,在操作結(jié)束后已完成編碼
        if CGImageDestinationFinalize(imgDestinationSource){//return true表示編碼成功,false則編碼失敗
            getPropertiesWith(imageData: newData)
        }
    }

二、制作動(dòng)圖

以常用的GIF動(dòng)圖生成為例,組成動(dòng)圖的基本屬性有2點(diǎn):總的幀數(shù)和每幀的停留時(shí)間??値瑪?shù)決定了動(dòng)畫效果,每幀停留時(shí)間決定了動(dòng)畫的流暢度。
那么通過CGImageDestination生成動(dòng)圖,主要設(shè)置便是:
1.通過設(shè)置Properties來配置動(dòng)圖屬性
2.通過AddImage來添加動(dòng)圖的組成幀數(shù)

    func createAnimatedImg(){
        let loopCount = 1
        let frameCount = 60
        let image1 = UIImage(named: "IMG_0851.HEIC")
        let image2 = UIImage(named: "IMG_0868.PNG")
        //設(shè)置動(dòng)圖屬性,kCGImagePropertyGIFLoopCount:動(dòng)圖的執(zhí)行次數(shù),kCGImagePropertyGIFDelayTime:每一幀圖片的執(zhí)行(持續(xù))時(shí)間
        var fileProperties = [kCGImagePropertyGIFDictionary:[kCGImagePropertyGIFLoopCount: loopCount]]
        var frameProperties = [kCGImagePropertyGIFDictionary:[kCGImagePropertyGIFDelayTime: 1.0 / Double(frameCount)]]
        //設(shè)置文件保存路徑
        let filePath = String(format: "%@/%.0lf.gif", mainPath!, Date().timeIntervalSince1970)
        guard let destination =  CGImageDestinationCreateWithURL(URL(fileURLWithPath: filePath) as CFURL,kUTTypeGIF as CFString, frameCount, nil) else {
            print(stderr, "Fail to create imgDestination");
            return
        }
         
        CGImageDestinationSetProperties(destination, fileProperties as CFDictionary)
         //向Destination中添加圖片,添加數(shù)量決定總幀數(shù)
        for i in 0..<frameCount {
            autoreleasepool {
                let radians = M_PI * 2.0 * Double(i) / Double(frameCount)
                let image = i%2 == 0 ? image1 : image2

                if let cropImg = cropImageWith(size: CGSize(width: 300, height: 300), origalImg: image!){
                    CGImageDestinationAddImage(destination, cropImg, frameProperties as CFDictionary)
                }
            }
        }
         //結(jié)束添加
        if CGImageDestinationFinalize(destination) {
            //進(jìn)行數(shù)據(jù)驗(yàn)證,這里是通過解碼查看元數(shù)據(jù)進(jìn)行的校驗(yàn),依個(gè)人喜好也可以通過加載來校驗(yàn)
            //getPropertiesWith(filePath: filePath)
        }
    }
    //使用的原圖過大,進(jìn)行了尺寸裁剪
    func cropImageWith(size : CGSize ,origalImg : UIImage) -> CGImage?{
       return origalImg.cgImage!.cropping(to: CGRect(origin: CGPoint(x: (origalImg.size.width - size.width)/2, y: (origalImg.size.height - size.height)/2), size: size));
    }
Apple官方文檔:文檔地址ImageIOGuide
參考的博客 iOS中的imageIO與image解碼
ImageIO的使用之CGImageSource圖像解碼
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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