Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access animated GIF's frames

I have an animated GIF successfully loaded into an NSData or NSBitmapImageRep object. Reference for NSBitmapImageRep

I've figured how to return data like the number of frames in that gif using:

NSNumber *frames = [bitmapRep valueForProperty:@"NSImageFrameCount"];

However, I'm a bit confused as to how I can actually access that frame as its own object.

I think one of these two methods will help, but I'm not actually sure how they'll get the individual frame for me.

+ representationOfImageRepsInArray:usingType:properties:
– representationUsingType:properties:

Any help appreciated. Thanks

like image 751
user339946 Avatar asked Oct 11 '25 19:10

user339946


1 Answers

I've figured how to return data like the number of frames in that gif using:

NSNumber *frames = [bitmapRep valueForProperty:@"NSImageFrameCount"];

However, I'm a bit confused as to how I can actually access that frame as its own object.

To have access to a special frame indexOfFrame ( 0 <= indexOfFrame < [frames intValue] ) you only need to set the NSImageCurrentFrame and you are done. There is no need to use CG-functions or make copies of frames. You can stay in the object oriented Cocoa world. A small example shows the duration of all GIF frames:

NSNumber *frames = [bitmapRep valueForProperty:@"NSImageFrameCount"];
if( frames!=nil ){   // bitmapRep is a Gif imageRep
   for( NSUInteger i=0; i<[frames intValue]; i++ ){
      [bitmapRep setProperty:NSImageCurrentFrame
                   withValue:[NSNumber numberWithUnsignedInt:i] ];
       NSLog(@"%2d duration=%@",
                 i, [bitmapRep valueForProperty:NSImageCurrentFrameDuration] );
   }
}

Another example: write all frames of a GIF image as PNG files to the filesystem:

NSNumber *frames = [bitmapRep valueForProperty:@"NSImageFrameCount"];
if( frames!=nil ){   // bitmapRep is a Gif imageRep
   for( NSUInteger i=0; i<[frames intValue]; i++ ){
      [bitmapRep setProperty:NSImageCurrentFrame
                   withValue:[NSNumber numberWithUnsignedInt:i] ];
       NSData *repData = [bitmapRep representationUsingType:NSPNGFileType
                                                 properties:nil];
       [repData writeToFile:
            [NSString stringWithFormat:@"/tmp/gif_%02d.png", i ] atomically:YES];
    }
}
like image 196
Heinrich Giesen Avatar answered Oct 14 '25 21:10

Heinrich Giesen