-1

I'm trying to convert my UIImage from a UIImageView to a string as the data is stored as Base64. I'm using the method below to convert the image but it falls over when trying to update convertedStr.

func convertImg() {
    let imageData: NSData = UIImagePNGRepresentation(imageView.image!)! as NSData
    convertedStr = NSString(data: imageData as Data, encoding: String.Encoding.utf8.rawValue)!
}

This function is about version 10 as I've tried different ways but the result is always the same. The error returned is

'fatal error: unexpectedly found nil while unwrapping an Optional value' and

'function signature specialization ) -> () to @callee_owned (@unowned Swift.UnsafeBufferPointer) -> (@out ()), Argument Types : [@callee_owned (@unowned Swift.UnsafeBufferPointer) -> ()]> of generic specialization of Swift.StaticString.withUTF8Buffer ((Swift.UnsafeBufferPointer) -> A) -> A'

Could it be that the method I'm using requires a png file and won't work with UIImage?

Janmenjaya
  • 4,149
  • 1
  • 23
  • 43
user616076
  • 3,907
  • 8
  • 38
  • 64
  • 2
    (NS)Data has a `base64EncodedString()` method which might be what you are looking for. – Interpreting pixel data as UTF-8 string can only fail. – Martin R Oct 19 '16 at 11:21
  • need to post image in server ? – KKRocks Oct 19 '16 at 11:22
  • check this : http://stackoverflow.com/questions/11251340/convert-between-uiimage-and-base64-string?answertab=votes#tab-top – KKRocks Oct 19 '16 at 11:23

2 Answers2

1
func convertImg() {
    let imageData: NSData = UIImagePNGRepresentation(imageView.image!)! as NSData
    convertstr = imageData.base64EncodedString(options: lineLength64Characters)

}
Naveen Ramanathan
  • 2,166
  • 1
  • 19
  • 21
1

In Swift

Encode in swift 2.0 and lower

let image : UIImage = UIImage(named:"imageNameHere")!
//Now use image to create into NSData format
let imageData:NSData = UIImagePNGRepresentation(image)!

 let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

Decode

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
print(decodedimage)
yourImageView.image = decodedimage
Mohit
  • 126
  • 2
  • 10