-1

I want to encode a UIImage object into Base64 String. Generally, I'm a getting quite a large string and the process is taking a long execustion time as well.

func convertImageToBase64String () -> String {
    guard let imageData: Data = UIImage.jpegData()
    let imgString = imageData.base64EncodedString(options: .init(rawValue: 0))
    return imgString
}

class func convertBase64StringToImage (imageBase64String: String) -> UIImage? {
    guard let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0)) else { return nil }
    let image = UIImage(data: imageData)
    return image
}

Please provide me a li'l help here.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Peeyush karnwal
  • 622
  • 7
  • 24
  • If someone manages to do that ... he'll probably get a Nobel prize; it also means he has found the best method for archiving/compress images – TonyMkenu May 07 '19 at 06:53
  • @rmaddy So is there any way I can reduce the pixel resolution to 4x4? – Peeyush karnwal May 07 '19 at 07:48
  • @TonyMkenu We programmers are supposed to provide the solution mate. "If someone manages to do that ... he'll probably get a Nobel prize" If it's that difficult or impossible, one should give it a try. Anywayz thanks !! – Peeyush karnwal May 07 '19 at 07:49

1 Answers1

1

What you want isn't possible. The JPEG data is already a compressed form of the image. And when you convert data to base64 encoding, the result is a string that will be 33% larger than the original data.

So the only way to get a base64 encoded string representation of a JPEG image that is less than 100 characters is to ensure that the original JPEG is less than 66 bytes. I'm pretty sure that even a 1x1 pixel JPEG will be more than 66 bytes.

If the JPEG is a full photograph taken on an iOS device, the resulting data will be a few megabytes. That takes time to submit.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks, Mate !! What if I'm okay with highly lossy compression. I mean, JPEG Compression is one way of achieving this (actually failing). But any other way like first reducing the resolution or anything else ? – Peeyush karnwal May 07 '19 at 07:51
  • Please re-read my answer. Even a 1x1 image will be larger than 100 bytes. You can scale the image to a manageable size and you can get its JPEG data with the highest compression to minimize the amount of data, but it will still be much larger than 100 bytes. There is absolutely no way encode a JPEG image and be less than 100 characters. – rmaddy May 07 '19 at 15:38