Преобразование изображения Gif в NSData

У меня есть GIF-изображение в моем фотоальбоме. Когда я использую UIImagePickerController для выбора этого изображения, мне нужно преобразовать изображение в NSData для сохранения.

Ранее я использовал

NSData *thumbData = UIImageJPEGRepresentation(thumbnail, 0.5);

но это не будет работать с изображениями gif. thumbData будет равно нулю.

  1. Как я могу получить NSData из изображения GIF?

  2. Как я могу узнать, что это GIF-изображение, требующее специальной обработки?


person wjh    schedule 25.05.2013    source источник
comment
Вы также использовали UIImagePNGRepresentation (миниатюра); ?   -  person Areal-17    schedule 25.05.2013
comment
взгляните на эту ссылку. Это может быть полезно для вас.   -  person George    schedule 25.05.2013
comment
Решили вашу проблему?   -  person Varun Naharia    schedule 17.10.2017


Ответы (5)


Ключевым моментом здесь является сохранение файла GIF или загрузки URL-адреса непосредственно в NSData вместо того, чтобы делать его UIImage. Обход UIImage позволит файлу GIF сохранить анимацию.

Вот некоторый код для преобразования файла GIF в NSData:

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

NSData *gifData = [NSData dataWithContentsOfFile: filePath];

Но, честно говоря, вам действительно следует подумать о том, чтобы вообще не использовать GIF.

person sangony    schedule 25.05.2013

Быстрый

Gif не должен не быть в активах.

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

Код для обложки файла .GIF можно конвертировать в NSdata -

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

NSData *dataOfGif = [NSData dataWithContentsOfFile: pathForFile];

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

  1. Тем, кто ищет быстрый ответ на этот вопрос, вот расширение UIImage, которое выполняет эту работу.
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. Хотя приведенное выше расширение сделает свою работу, обработка gif из средства выбора изображений проще, вот реализация в функции 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
    }
}

с использованием функции расширения в 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