简体   繁体   中英

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++ .
The problem is that if I resize the image by 512x512 (that's the resolution I need) it crashes: 在此处输入图片说明 If I resize the image (either with OpenCV either with Swift) to another resolution (ex 510x510) it doesn't crash.

The strange thing is that on the simulator it never crashes while on the iPhone XS it crashes 90% of the times.

How can I convert a PNG to a Webp in Swift?
Why is OpenCV crashing on the imwrite instruction if the Mat is 512x512?

UPDATE :
OpenCV version: 3.4.2
I found out that this problem happens when the PNG image get processed before from the Core Graphics framework. I need to use it since I save a UIVIew as UIImage this way:

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 😊

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

pod both 'SDWebImage' AND 'SDWebImage/WebP'

import SDWebImage

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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