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()
    }

}
4

1 回答 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 }
于 2019-12-05T11:16:08.667 回答