Konversikan gambar Gif ke NSData

Saya memiliki gambar gif di album foto saya. Saat saya menggunakan UIImagePickerController untuk memilih gambar itu, saya perlu mengonversi gambar menjadi NSData untuk disimpan.

Sebelumnya, saya menggunakan

NSData *thumbData = UIImageJPEGRepresentation(thumbnail, 0.5);

tapi itu tidak akan berfungsi dengan gambar gif. thumbData akan menjadi nihil.

  1. Bagaimana saya bisa mendapatkan NSData dari gambar gif?

  2. Bagaimana saya bisa tahu bahwa itu adalah gambar gif yang memerlukan penyerahan khusus?


person wjh    schedule 25.05.2013    source sumber
comment
Apakah Anda juga menggunakan UIImagePNGRepresentation(thumbnail); ?   -  person Areal-17    schedule 25.05.2013
comment
lihat tautan ini. Ini mungkin berguna bagi Anda.   -  person George    schedule 25.05.2013
comment
Sudah menyelesaikan masalahmu?   -  person Varun Naharia    schedule 17.10.2017


Jawaban (5)


Kuncinya di sini adalah menyimpan file GIF atau URL unduhan langsung ke NSData alih-alih menjadikannya UIImage. Melewati UIImage akan membiarkan file GIF mempertahankan animasinya.

Berikut beberapa kode untuk mengubah file GIF menjadi NSData:

NSString *filePath = [[NSBundle mainBundle] pathForResource: @"gifFileName" ofType: @"gif"];

NSData *gifData = [NSData dataWithContentsOfFile: filePath];

Namun sejujurnya, Anda harus mempertimbangkan untuk tidak menggunakan GIF sama sekali.

person sangony    schedule 25.05.2013

Cepat

Gif tidak boleh berada dalam aset.

let path = Bundle.main.path(forResource: "loader", ofType: "gif")!
let data = try! Data(contentsOf: URL(fileURLWithPath: path))
return data
person Nik Kov    schedule 20.03.2018

https://github.com/mattt/AnimatedGIFImageSerialization

UIImage *image = ...;
NSData *data = [AnimatedGIFImageSerialization animatedGIFDataWithImage:image
                                                              duration:1.0
                                                             loopCount:1
                                                                 error:nil];
person ProBlc    schedule 11.04.2017

Kode untuk menutupi file .GIF dapat dikonversi di NSdata -

NSString *pathForFile = [[NSBundle mainBundle] pathForResource: @"myGif" ofType: @"gif"];

NSData *dataOfGif = [NSData dataWithContentsOfFile: pathForFile];

NSLog(@"Data: %@", dataOfGif);
person RMRAHUL    schedule 25.05.2013

  1. Bagi mereka yang mencari jawaban cepat untuk pertanyaan ini, inilah ekstensi UIImage yang berfungsi.
import UIKit
import MobileCoreServices

extension UIImage {
    func UIImageAnimatedGIFRepresentation(gifDuration: TimeInterval = 0.0, loopCount: Int = 0) throws -> Data {
        let images = self.images ?? [self]
        let frameCount = images.count
        let frameDuration: TimeInterval = gifDuration <= 0.0 ? self.duration / Double(frameCount) : gifDuration / Double(frameCount)
        let frameDelayCentiseconds = Int(lrint(frameDuration * 100))
        let frameProperties = [
            kCGImagePropertyGIFDictionary: [
                kCGImagePropertyGIFDelayTime: NSNumber(value: frameDelayCentiseconds)
            ]
        ]

        guard let mutableData = CFDataCreateMutable(nil, 0),
           let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeGIF, frameCount, nil) else {
            throw NSError(domain: "AnimatedGIFSerializationErrorDomain",
                          code: -1,
                          userInfo: [NSLocalizedDescriptionKey: "Could not create destination with data."])
        }
        let imageProperties = [
            kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFLoopCount: NSNumber(value: loopCount)]
        ] as CFDictionary
        CGImageDestinationSetProperties(destination, imageProperties)
        for image in images {
            if let cgimage = image.cgImage {
                CGImageDestinationAddImage(destination, cgimage, frameProperties as CFDictionary)
            }
        }

        let success = CGImageDestinationFinalize(destination)
        if !success {
            throw NSError(domain: "AnimatedGIFSerializationErrorDomain",
                          code: -2,
                          userInfo: [NSLocalizedDescriptionKey: "Could not finalize image destination"])
        }
        return mutableData as Data
    }
}
  1. Meskipun ekstensi di atas dapat berfungsi, menangani gif dari pemilih gambar lebih sederhana, berikut implementasi dalam fungsi UIImagePickerControllerDelegate.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    let info = Dictionary(uniqueKeysWithValues: info.map {key, value in (key.rawValue, value)})
    if let url = info[UIImagePickerController.InfoKey.referenceURL.rawValue] as? URL, url.pathExtension.lowercased() == "gif" {
       picker.dismiss(animated: false, completion: nil)
       url.getGifImageDataFromAssetUrl(completion: { imageData in
           // Use imageData here.
       })
       return
    }
}

dengan menggunakan fungsi ekstensi di URL

import UIKit
import Photos

extension URL {
    func getGifImageDataFromAssetUrl(completion: @escaping(_ imageData: Data?) -> Void) {
        let asset = PHAsset.fetchAssets(withALAssetURLs: [self], options: nil)
        if let image = asset.firstObject {
            PHImageManager.default().requestImageData(for: image, options: nil) { (imageData, _, _, _) in
                completion(imageData)
            }
        }
    }
}
person MMujtabaRoohani    schedule 04.03.2021