แปลงภาพ 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(thumbnail); หรือไม่ ?   -  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