Skip to content

已增加webp动图支持,附代码 #6

@XiFengLang

Description

@XiFengLang

iOS14的WebKit已经支持webp,所以只要在iOS13及下面的版本做兼容即可。

我没有详细取每一帧的duration,用的duration是平均值,遇到极个别动图会很慢,大部分图看不出什么异样。

增加或者修改下面的代码

  pod 'SDWebImage','>= 5.9'
  pod 'SDWebImageWebPCoder'


#import <MobileCoreServices/MobileCoreServices.h>

- (void)ba_registerURLProtocol
{
    if (@available(iOS 14.0, *)) { } else {
        [NSURLProtocol registerClass:NSClassFromString(@"BAURLSessionProtocol")];
        // 注册registerScheme使得WKWebView支持NSURLProtocol
        [NSURLProtocol ba_web_registerScheme:@"http"];
        [NSURLProtocol ba_web_registerScheme:@"https"];
    }
}

- (void)dealloc
{
    if (@available(iOS 14.0, *)) {} else {
        [NSURLProtocol unregisterClass:NSClassFromString(@"BAURLSessionProtocol")];
        // 移除 registerScheme
        [NSURLProtocol ba_web_unregisterScheme:@"http"];
        [NSURLProtocol ba_web_unregisterScheme:@"https"];
    }
}


- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error{
    
    if (error) {
        [self.client URLProtocol:self didFailWithError:error];
    }else{
        if ([task.currentRequest.URL.absoluteString hasSuffix:@"webp"]) {
            // 如果判断是需要处理的webp图片,就对图片进行转换
            NSLog(@"webp---%@",task.currentRequest.URL);
            UIImage *imgData = [UIImage sd_imageWithWebPData:self.imageData];
            NSArray * images = imgData.images;
            
            if (images.count > 1) {
                NSTimeInterval duration = imgData.duration / images.count;

                NSString * fileName = [[task.currentRequest.URL URLByDeletingPathExtension] lastPathComponent];
                NSString *cashPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.gif",fileName]];
                NSURL *url = [NSURL fileURLWithPath:cashPath];

                // 设置gif的彩色空间格式、颜色深度、执行次数
                NSDictionary *gifDic = @{
                    (NSString *)kCGImagePropertyGIFLoopCount:@(0),
                    (NSString *)kCGImagePropertyColorModel:(NSString *)kCGImagePropertyColorModelRGB,
                    (NSString *)kCGImagePropertyDepth:@(16)
                };
                NSDictionary *gifProperties = @{(NSString *)kCGImagePropertyGIFDictionary:gifDic};
                CGImageDestinationRef destination = CGImageDestinationCreateWithURL((CFURLRef)url, kUTTypeGIF, images.count, NULL);
                CGImageDestinationSetProperties(destination, (CFDictionaryRef)gifProperties);
                
                for (int32_t index = 0; index < images.count; index ++) {
                    UIImage * frame = [images objectAtIndex:index];
                    NSDictionary * gifDict = @{
                        (NSString *)kCGImagePropertyGIFDelayTime:@(duration)
                    };
                    NSDictionary * frameProperties = @{
                        (NSString *)kCGImagePropertyGIFDictionary:gifDict
                    };
                    CGImageDestinationAddImage(destination, frame.CGImage, (CFDictionaryRef)frameProperties);
                }
            
                CGImageDestinationFinalize(destination);
                CFRelease(destination);
                NSData *transData = [NSData dataWithContentsOfFile:cashPath];
                self.beginAppendData = NO;
                self.imageData = nil;
                [self.client URLProtocol:self didLoadData:transData];
            } else {
                NSData *transData = UIImageJPEGRepresentation(imgData, 0.8f);
                self.beginAppendData = NO;
                self.imageData = nil;
                [self.client URLProtocol:self didLoadData:transData];
            }
        }
        [self.client URLProtocolDidFinishLoading:self];
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions