简体   繁体   English

如何在Swift中将PNG转换为WebP?

[英]How to convert a PNG to a WebP in Swift?

I'm trying to convert a PNG image in Webp in Swift, the only framework I got working is OpenCV through Objective-c++ . 我正在尝试在Swift中的Webp中转换PNG图像,我使用的唯一框架是通过Objective-c ++的 OpenCV
The problem is that if I resize the image by 512x512 (that's the resolution I need) it crashes: 问题是,如果我将图像调整为512x512(这是我需要的分辨率),则会崩溃: 在此处输入图片说明 If I resize the image (either with OpenCV either with Swift) to another resolution (ex 510x510) it doesn't crash. 如果我将图像大小调整(使用OpenCV或Swift调整大小)到另一个分辨率(例如510x510),它都不会崩溃。

The strange thing is that on the simulator it never crashes while on the iPhone XS it crashes 90% of the times. 奇怪的是,在模拟器上它从未崩溃,而在iPhone XS上,它崩溃了90%。

How can I convert a PNG to a Webp in Swift? 如何在Swift中将PNG转换为Webp?
Why is OpenCV crashing on the imwrite instruction if the Mat is 512x512? 如果Mat是512x512,为什么OpenCV在imwrite指令上崩溃?

UPDATE : 更新
OpenCV version: 3.4.2 OpenCV版本:3.4.2
I found out that this problem happens when the PNG image get processed before from the Core Graphics framework. 我发现从Core Graphics框架之前处理PNG图像时会发生此问题。 I need to use it since I save a UIVIew as UIImage this way: 我需要使用它,因为我通过以下方式将UIVIew保存为UIImage:

let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }

I ended up using another framework to convert PNG to WebP: https://github.com/seanooi/iOS-WebP , had to create the wrapper to use it on swift but it works very good 😊 我最终使用了另一个框架将PNG转换为WebP: https : //github.com/seanooi/iOS-WebP ,不得不创建包装器才能快速使用它,但效果很好

My wrapper is very simple but does what I needed: 我的包装器非常简单,但是可以满足我的需求:

#import <Foundation/Foundation.h>
#import "WebPWrapper.h"
#import "UIImage+WebP.h"

@implementation WebPWrapper
-(NSData *)convertUIImageToWebp:(UIImage *)image :(int)quality {
    NSData *webPData = [UIImage imageToWebP:image quality:quality];
    return webPData;
}
@end

In swift I use it this way: 我以这种方式迅速使用它:

let webPData = WebPWrapper().convertUIImage(toWebp: image, 90)

Swift 4.0 迅捷4.0

pod both 'SDWebImage' AND 'SDWebImage/WebP' 吊舱'SDWebImage''SDWebImage/WebP'

import SDWebImage 导入SDWebImage

if let image_download = UIImage(data: data) {
   let photo:Data = image_download.sd_imageData(as: SDImageFormat.webP)!
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM