WebP解码支持(Objc & Swift)
2018-08-02 本文已影响0人
Jadian
Swift版本
步骤:
- 下载 WebpFramework-1.0.0
- 仅导入
decoder
- 在
swift项目
中,随便创建objc
文件,以便自动生成桥接用的头文件,删除无用的.m
文件- 在
XXX-Bridging-Header.h
中,写入#import <WebPDecoder/decode.h>
- 添加
UIImage+Webp.swift
,代码如下
//
// UIImage+Webp.swift
// FileShare
//
// Created by JadianZheng on 2018/7/26.
// Copyright © 2018 JadianZheng. All rights reserved.
//
import UIKit
private func freeWebPData(info: UnsafeMutableRawPointer?, data: UnsafeRawPointer, size: Int) -> Void {
free(UnsafeMutableRawPointer(mutating: data))
}
extension UIImage {
convenience init?(webPPath path: String) {
guard let imageData = NSData(contentsOfFile: path) else {
return nil
}
var width: CInt = 0
var height: CInt = 0
let rgbaData = WebPDecodeRGBA(imageData.bytes.assumingMemoryBound(to: UInt8.self), imageData.length, &width, &height)
let provider = CGDataProvider(dataInfo: nil, data: rgbaData!, size: Int(width) * Int(height) * 4, releaseData: freeWebPData)
let bitmapWithAlpha = CGBitmapInfo(rawValue: CGImageAlphaInfo.last.rawValue)
if let cgimage = CGImage(width:Int(width),
height:Int(height),
bitsPerComponent: 8,
bitsPerPixel: 32,
bytesPerRow: 4 * Int(width),
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: bitmapWithAlpha,
provider: provider!,
decode: nil,
shouldInterpolate: true,
intent: CGColorRenderingIntent.defaultIntent) {
self.init(cgImage: cgimage)
}
else {
return nil
}
}
}
Object-C 版本
步骤:
- 下载 WebpFramework-1.0.0
- 仅导入
decoder
- 添加
UIImage
类别,如下:
//
// UIImage+WebP.h
// Webp
//
// Created by JadianZheng on 2018/8/2.
// Copyright © 2018 JadianZheng. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIImage (WebP)
+ (UIImage*)imageWithWebp:(NSURL*)fileURL;
@end
NS_ASSUME_NONNULL_END
//
// UIImage+WebP.m
// Webp
//
// Created by JadianZheng on 2018/8/2.
// Copyright © 2018 JadianZheng. All rights reserved.
//
#import "UIImage+WebP.h"
#import <WebPDecoder/decode.h>
@implementation UIImage (WebP)
static void free_image_data(void *info, const void *data, size_t size) {
free((void*) data);
}
+ (UIImage*)imageWithWebp:(NSURL*)fileURL {
NSData *imageData = [NSData dataWithContentsOfURL:fileURL];
int width = 0, height = 0;
uint8_t* data = WebPDecodeRGBA(imageData.bytes, imageData.length, &width, &height);
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, data, width * 4 * height, free_image_data);
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGImageRef imageRef = CGImageCreate(width, height, 8, 32, 4 * width,
colorSpaceRef, kCGBitmapByteOrderDefault, provider, NULL, NO, kCGRenderingIntentDefault);
UIImage *result = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CGColorSpaceRelease(colorSpaceRef);
CGDataProviderRelease(provider);
return result;
}
@end