3

I have a UIImage which is a GIF file.

I need to make it make it into an NSData object. But it needs to stay a GIF so I can't use UIImageJPEGRepresentation.

Any ideas?

Cocoadelica
  • 3,006
  • 27
  • 30

3 Answers3

15

Once it's a UIImage, it's not a gif anymore. It's already been interpreted into a core graphics image object, wrapped in the UIKit trimmings of UIImage. You DON'T have a UIImage that "is a GIF". It may have been once, but that time has passed.

If you're downloading this thing (which I assume by your comment "I don't have access to the file"), then you should download it as data, and keep it as data, and if you make a UIImage based on that data, you maybe need to keep the data around.

(This is all a guess, though, because you're dribbling out details about your question drip by drip. If you could say in a bigger breath what you want to accomplish, we can probably help better.)

Dan Ray
  • 21,623
  • 6
  • 63
  • 87
9

I faced the same issue you mention and here is the code i used to save the animated gif to Photos without losing animation:

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

NSData *data = [NSData dataWithContentsOfURL:[self getCurrentGIFURL]];

[library writeImageDataToSavedPhotosAlbum:data metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {}

Basically, if you save the gif from URL or from file directly as an NSData object instead of making it a UIImage, it will keep the animation.

Chintan Patel
  • 3,175
  • 3
  • 30
  • 36
2

You could load it into a NSData* directly if you know the filepath. Such as:

NSData *gifData = [NSData dataWithContentsOfFile:@"myCoolPic.gif"];

NSData dataWithContentsOfFile docs

Sam
  • 26,946
  • 12
  • 75
  • 101
  • this is true but it's not that easy sadly... I don't have access to the file. – Cocoadelica Sep 14 '11 at 17:24
  • 3
    So how are you getting the image then? – darksky Sep 14 '11 at 17:40
  • 3
    Huh? not having access to the file most definitely stops you from loading it into NSData... in addition to viewing it, using it, manipulating it, and doing ..well pretty much anything with it. – Zigglzworth Sep 14 '11 at 18:34
  • I'm given it as NSData but it's direct from AVCapture not from a file – Cocoadelica Sep 16 '11 at 07:56
  • 2
    I had to use this to get the data from file: `NSString* gifPath = [[NSBundle mainBundle] pathForResource:@"ajax-loader" ofType:@"gif"];` and supply this string to the function above. – Martin Berger Sep 21 '12 at 09:54