Convert between UIImage and Base64 string

2018-12-31 05:02发布

Does anyone know how to convert a UIImage to a Base64 string, and then reverse it?

I have the below code; the original image before encoding is good, but I only get a blank image after I encode and decode it.

NSData *imageData = UIImagePNGRepresentation(viewImage);

NSString *b64EncStr = [self encode: imageData];

NSString *base64String = [self encodeBase64:imageData];

19条回答
栀子花@的思念
2楼-- · 2018-12-31 05:27

SWIFT 3.0, XCODE 8.0

Replace String with your URL. and testImage is an outlet of ImageView

// Put Your Image URL
let url:NSURL = NSURL(string : "http://.jpg")!
// It Will turn Into Data
let imageData : NSData = NSData.init(contentsOf: url as URL)!
// Data Will Encode into Base64
let str64 = imageData.base64EncodedData(options: .lineLength64Characters)
// Now Base64 will Decode Here
let data: NSData = NSData(base64Encoded: str64 , options: .ignoreUnknownCharacters)!
// turn  Decoded String into Data
let dataImage = UIImage(data: data as Data)
// pass the data image to image View.:)
testImage.image = dataImage

Hope It Helps Thanks.

查看更多
时光乱了年华
3楼-- · 2018-12-31 05:27
@implementation UIImage (Extended)

- (NSString *)base64String {
    NSData * data = [UIImagePNGRepresentation(self) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return [NSString stringWithUTF8String:[data bytes]];
}

@end
查看更多
深知你不懂我心
4楼-- · 2018-12-31 05:28

In swift 2.0 use this extension (credit to Jonas Franz)

extension UIImage{
  func toBase64() -> String{
    let imageData = UIImagePNGRepresentation(self)!
    return imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
  }
}
查看更多
低头抚发
5楼-- · 2018-12-31 05:28

Swift-Extension:

extension UIImage{
     func toBase64() -> String{
          var imageData = UIImagePNGRepresentation(self)
          return imageData.base64EncodedStringWithOptions(.allZeros)
     }
}
查看更多
浪荡孟婆
6楼-- · 2018-12-31 05:28

I tried all the solutions, none worked for me (using Swift 4), this is the solution that worked for me, if anyone in future faces the same problem.

let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options: 
 .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)

yourImage.image = decodedimage
查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 05:28

Swift 4.2, Xcode 10.1

let imageData = UIImage(named:"imagename").pngData()?.base64EncodedString(options: .lineLength64Characters)

print(imageData)

查看更多
登录 后发表回答