-1

My scenario, I am trying to get Image data for upload to server. Here, I am getting huge data string length. Is there anything possibility to get short string without reducing image file resolution.

My Code for Image Data

let image = self.attachment_one_img.image
let imageData = image?.jpegData(compressionQuality: 1)
let base64String = (imageData)?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let trimmedString_one = base64String?.trimmingCharacters(in: .whitespaces)
Print(trimmedString_one) // I am getting huge data string length 
jackios
  • 155
  • 2
  • 11
  • related https://stackoverflow.com/questions/29137488/how-do-i-resize-the-uiimage-to-reduce-upload-image-size/29138120?r=SearchResults&s=1|42.5093#29138120 and https://stackoverflow.com/a/29726675/2303865 – Leo Dabus Mar 08 '19 at 14:52
  • 1
    Not related to your question but you should drop use Swift native data type. No need to use NSData since Swift 3. `base64EncodedString()` and there is no need to trim white spaces – Leo Dabus Mar 08 '19 at 14:55

1 Answers1

1

Base-64 adds approximately 33% overhead to whatever its input data is. The only way to make it smaller is shrink your input data.

You can use other ASCII-based encodings, such as Ascii85, which have a little less overhead, but the encoded data will always be larger than the input data, because you're using fewer bits-per-byte to hold it (fewer bits-per-byte means more bytes for the same number of input bits). Since image data is typically already well compressed, it cannot be sent in significantly fewer bytes types than its data representations.

If it is JPEG data, you can reduce the quality rather than the resolution. Using a compression quality of 1 is generally excessive, and you should consider PNG rather than JPEG if you're looking for lossless compression. (JPEG is intended for photographs, and is very good at compressing them. PNG is generally better for line-art and other things with very sharp color transitions.) After ensuring your resolution is no higher than needed, tuning the quality value is the best tool for managing size.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610