Convert Gif image to NSData

2019-06-16 05:57发布

问题:

I have a gif image in my photo album. When I use the UIImagePickerController to select that image, I need to convert the image to NSData for storing.

Earlier, I used

NSData *thumbData = UIImageJPEGRepresentation(thumbnail, 0.5);

but it will not work with gif images. thumbData will be nil.

  1. How can I get NSData from the gif image?

  2. How can I know that it is a gif image that needs special handing?

回答1:

The key here is to save the GIF file or URL download directly into a NSData instead of making it a UIImage. Bypassing UIImage will let the GIF file keep the animation.

Here is some code to convert a GIF file into NSData:

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

NSData *gifData = [NSData dataWithContentsOfFile: filePath];

But in all honesty, you should really consider not using GIF at all.



回答2:

Swift

Gif must not be in assets.

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


回答3:

Code to coverting .GIF file can converted in NSdata -

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

NSData *dataOfGif = [NSData dataWithContentsOfFile: pathForFile];

NSLog(@"Data: %@", dataOfGif);


回答4:

https://github.com/mattt/AnimatedGIFImageSerialization

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


标签: ios nsdata gif