Search code examples
iosswiftbase64uiimage

How to set width and height in an image converted from a base64 string?


I have a question about UIImage convert to base64 String.
I resize my image width and height (1024 x 768) and then convert this image to a base64 string. But when I convert this base64 string back to UIImage and look at the image width and height, it is not resized as before(2304.0 x 3072.0).
How to make my base64 String image size correctly?

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

}

Solution

  • Try this way, the below code resizes your image, and should be added before you change it to 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 }