分解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代码中没有进行保存到手机相册中,如果需要自己写入就好

展开阅读全文

没有更多推荐了,返回首页