如何访问动画GIF的帧

use*_*946 3 macos cocoa core-graphics objective-c core-image

我有一个动画GIF成功加载到一个NSData或一个NSBitmapImageRep对象.NSBitmapImageRep的参考

我已经想过如何使用以下方法返回数据,例如该gif中的帧数:

NSNumber *frames = [bitmapRep valueForProperty:@"NSImageFrameCount"];
Run Code Online (Sandbox Code Playgroud)

但是,我对如何实际访问该帧作为自己的对象感到困惑.

我认为这两种方法中的一种会有所帮助,但我不确定他们将如何为我提供个性化的框架.

+ representationOfImageRepsInArray:usingType:properties:
– representationUsingType:properties:
Run Code Online (Sandbox Code Playgroud)

任何帮助赞赏.谢谢

小智 7

我已经想过如何使用以下方法返回数据,例如该gif中的帧数:

NSNumber *frames = [bitmapRep valueForProperty:@"NSImageFrameCount"];
Run Code Online (Sandbox Code Playgroud)

但是,我对如何实际访问该帧作为自己的对象感到困惑.

要访问特殊框架indexOfFrame(0 <= indexOfFrame < [frames intValue]),您只需设置NSImageCurrentFrame并完成.无需使用CG功能或制作帧的副本.你可以留在面向对象的Cocoa世界.一个小例子显示了所有GIF帧的持续时间:

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] );
   }
}
Run Code Online (Sandbox Code Playgroud)

另一个例子:将GIF图像的所有帧作为PNG文件写入文件系统:

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];
    }
}
Run Code Online (Sandbox Code Playgroud)