分解gif图片并保存

本文介绍了一种使用Objective-C分解GIF文件并将其各帧保存为独立图片的方法。通过CGImageSource创建源对象,获取GIF文件的所有帧,并转换为UIImage格式进行保存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/** Gif的步骤
 1. 拿到Gifd的数据
 2. 将Gif分解为一帧帧
 3. 将单帧数据转为UIImage
 4. 单帧图片保存
 */
#import <ImageIO/ImageIO.h>     // 图像的输入输出文件
#import <MobileCoreServices/MobileCoreServices.h>
- (void)didCompositionGif {

    //1. 拿到gif数据
    NSString * gifPathSource = [[NSBundle mainBundle] pathForResource:@"kobe" ofType:@"gif"];
    NSData * data = [NSData dataWithContentsOfFile:gifPathSource];
#warning 桥接的意义 (__bridge CFDataRef)

    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    
    //2. 将gif分解为一帧帧
    size_t count = CGImageSourceGetCount(source);
    NSLog(@"%zu",count);
    
    NSMutableArray * tmpArray = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < count; i ++) {
        CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, i, NULL);
        
        //3. 将单帧数据转为UIImage
        UIImage * image = [UIImage imageWithCGImage:imageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
        [tmpArray addObject:image];
#warning CG类型的对象 不能用ARC自动释放内存.需要手动释放
        CGImageRelease(imageRef);
    }
    CFRelease(source);
    
    // 单帧图片保存
    int i = 0;
    for (UIImage * image  in tmpArray) {
        
        i ++;
        NSData * data = UIImagePNGRepresentation(image);
        NSArray * path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString * gifPath = path[0];
        NSLog(@"gifPath: %@",gifPath);
        NSString * pathNum = [gifPath stringByAppendingString:[NSString stringWithFormat:@"%d.png",i]];
        [data writeToFile:pathNum atomically:NO];
    }
}

 

转载于:https://www.cnblogs.com/edensyd/p/9198278.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值