如何设置base64字符串转换的图像的宽度和高度?

问题描述 投票:0回答:1

我有一个关于 UIImage 转换为 base64 字符串的问题。
我调整图像的宽度和高度 (1024 x 768) 并 然后将此图像转换为 Base64 字符串。 但是当我将此 base64 字符串转换回 UIImage 并查看图像宽度和高度时,它并没有像以前那样调整大小(2304.0 x 3072.0)。
如何正确设置我的 base64 字符串图像大小?

guard let image = image else { return }
print("image => \(image)") 
//image => <UIImage:0x283cce7f0 anonymous {768, 1024}>

guard let base64ImageString = image.toBase64(format: .jpeg(0.2)) else { return }
            
let dataDecoded : Data = Data(base64Encoded: base64ImageString, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
let height = decodedimage?.size.height
let width = decodedimage?.size.width
print("====) \(String(describing: width)) / \(String(describing: height))")
//====) Optional(2304.0) / Optional(3072.0)
public enum ImageFormat {
    case png
    case jpeg(CGFloat)
}

extension UIImage {

    public func toBase64(format: ImageFormat) -> String? {
        var imageData: Data?
        
        switch format {
        case .png:
            imageData = self.pngData()
        case .jpeg(let compression):
            imageData = self.jpegData(compressionQuality: compression)
        }
        
        return imageData?.base64EncodedString()
    }

}
ios swift base64 uiimage
1个回答
0
投票

尝试这种方式,下面的代码会调整您的图像大小,并且应该在将其更改为 base64 之前添加。

guard let image = image else { return }
print("image => \(image)") 
//image => <UIImage:0x283cce7f0 anonymous {768, 1024}>

let desiredSize = CGSize(width: 768, height: 1024)

UIGraphicsBeginImageContextWithOptions(desiredSize, false, 1.0)
image.draw(in: CGRect(origin: CGPoint.zero, size: CGSize(width: 
desiredSize.width, height: desiredSize.height)))

let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

guard let base64ImageString = resizedImage.toBase64(format: .jpeg(0.2)) else { return }
© www.soinside.com 2019 - 2024. All rights reserved.