分解gif图片并保存

代码如下:

-(void)deCompositionGif{
    NSString *gitpathSource = [[NSBundle mainBundle]pathForResource:@"名称" ofType:@"gif"];
    NSData *data =[NSData dataWithContentsOfFile:gitpathSource];
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    //将gif分解成一帧帧
    size_t count = CGImageSourceGetCount(source);
    NSMutableArray *tmpArray =[[NSMutableArray alloc]init];
    for (size_t i = 0; i < count; i++) {
     CGImageRef imageref  =  CGImageSourceCreateImageAtIndex(source, 1, NULL);
        //将单帧数据转化成Image
        UIImage *image = [UIImage imageWithCGImage:imageref scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
        [tmpArray addObject:image];
        CGImageRelease(imageref);
    }
    CFRelease(source);

//前面两处释放是为了防止内存泄漏

    int i = 0;
    for (UIImage *image in tmpArray) {
        NSData *data = UIImagePNGRepresentation(image);
        NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *gifPath = path[0];
        NSString *pathNum = [gifPath stringByAppendingString:[NSString stringWithFormat:@"%d.png",i]];
        i++;
        [data writeToFile:pathNum atomically:NO];
    }
    
}



 

OC引入#import <ImageIO/ImageIO.h>

swift引入import ImageIO


swift代码:

 func deCompositionGif() {
        let gitpathSource = Bundle.main.path(forResource: "1", ofType: "gif")
        let data = NSData.init(contentsOfFile: gitpathSource!)
        
        let source = CGImageSourceCreateWithData(data!, nil)
            //将gif分解成一帧帧
        var count = CGImageSourceGetCount(source!)
        let tmpArray : NSMutableArray = []
        while count > 0 {
            let imageref = CGImageSourceCreateImageAtIndex(source!, 1, nil)

            let  image = UIImage.init(cgImage: imageref!, scale: UIScreen.main.scale, orientation: UIImageOrientation.up)
            count -= 1;
            tmpArray.add(image)
        }

        var i = 0
        
        for image in tmpArray {
            let data : NSData = UIImagePNGRepresentation(image as! UIImage)! as NSData
            let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
            let pathNum = path + "\(i).png";
                i += 1;
            data.write(toFile: pathNum, atomically: true);
            UIImageWriteToSavedPhotosAlbum(image as! UIImage, nil, nil, nil)
            
            }
            
      
    }

最重要的一点是比忘了添加 <key>NSPhotoLibraryUsageDescription</key> <string>App需要您的同意,才能访问相册</string>  iOS 10如果访问必须添加否则闪退

在OC代码中没有进行保存到手机相册中,如果需要自己写入就好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值