在UIImage和Base64字符串之间转换

有人知道如何将UIImage转换为Base64字符串,然后反转它吗?

我有以下代码;编码前的原始图像是好的,但编码解码后只得到一个空白图像。

NSData *imageData = UIImagePNGRepresentation(viewImage);


NSString *b64EncStr = [self encode: imageData];


NSString *base64String = [self encodeBase64:imageData];
293521 次浏览

斯威夫特

首先我们需要image的NSData

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


//OR next possibility


//Use image's path to create NSData
let url:NSURL = NSURL(string : "urlHere")!
//Now use image to create into NSData format
let imageData:NSData = NSData.init(contentsOfURL: url)!

Swift 2.0 >编码

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

Swift 2.0 >解码

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!

Swift 3.0 >解码

let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!

编码:

let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
print(strBase64)

解码:

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

斯威夫特3.0

let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImageView.image = decodedimage

objective - c

iOS7祝辞版本

你可以使用NSData's base64EncodedStringWithOptions

编码:

- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

解码:

- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}

iOS 6.1和<版本

第一个选项:使用链接到encodedecode图像

在你的project中添加Base64类。

编码:

 NSData* data = UIImageJPEGRepresentation(yourImage, 1.0f);
NSString *strEncoded = [Base64 encode:data];

解码:

 NSData* data = [Base64 decode:strEncoded ];;
image.image = [UIImage imageWithData:data];

另一个选择:对encodingdecoding使用QSUtilities


@implementation UIImage (Extended)


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


@end

对于iOS 7+, Objective-C,下面是如何从一个图像URL开始转换:

NSURL *url = [NSURL URLWithString:self.groove.thumbnailURL];


UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];


NSString *base64String = [UIImagePNGRepresentation(image)
base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

斯威夫特iOS8

// prgm mark ----


// convert images into base64 and keep them into string


func convertImageToBase64(image: UIImage) -> String {


var imageData = UIImagePNGRepresentation(image)
let base64String = imageData.base64EncodedStringWithOptions(.allZeros)


return base64String


}// end convertImageToBase64




// prgm mark ----


// convert images into base64 and keep them into string


func convertBase64ToImage(base64String: String) -> UIImage {


let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0) )


var decodedimage = UIImage(data: decodedData!)


return decodedimage!


}// end convertBase64ToImage

Swift-Extension:

extension UIImage{
func toBase64() -> String{
var imageData = UIImagePNGRepresentation(self)
return imageData.base64EncodedStringWithOptions(.allZeros)
}
}
See my class -  AppExtension.swift




// MARK: - UIImage (Base64 Encoding)


public enum ImageFormat {
case PNG
case JPEG(CGFloat)
}


extension UIImage {


public func base64(format: ImageFormat) -> String {
var imageData: NSData
switch format {
case .PNG: imageData = UIImagePNGRepresentation(self)
case .JPEG(let compression): imageData = UIImageJPEGRepresentation(self, compression)
}
return imageData.base64EncodedStringWithOptions(.allZeros)
}
}

在swift 2.0中使用此扩展(credit to Jonas Franz)

extension UIImage{
func toBase64() -> String{
let imageData = UIImagePNGRepresentation(self)!
return imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
}
}

Swift版本-创建base64镜像

在我看来,在UIImagePNGRepresenatation()的情况下隐式Unwrapped Optional是不安全的,所以我建议使用如下扩展:

extension UIImage {


func toBase64() -> String? {
let imageData = UIImagePNGRepresentation(self)
return imageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
}
}

Swift 3.0, xcode 8.0

将字符串替换为URL。和testImage是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

希望能有所帮助谢谢。

在Swift 3.0中

func decodeBase64(toImage strEncodeData: String) -> UIImage {


let dataDecoded  = NSData(base64Encoded: strEncodeData, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!
let image = UIImage(data: dataDecoded as Data)
return image!


}

在Swift 3.0和Xcode 8.0

编码:

let userImage:UIImage = UIImage(named: "Your-Image_name")!
let imageData:NSData = UIImagePNGRepresentation(userImage)! as NSData
let dataImage = imageData.base64EncodedString(options: .lineLength64Characters)

解码:

let imageData = dataImage
let dataDecode:NSData = NSData(base64Encoded: imageData!, options:.ignoreUnknownCharacters)!
let avatarImage:UIImage = UIImage(data: dataDecode as Data)!
yourImageView.image = avatarImage

Swift 3.0和Xcode 8.0

let imageData = UIImageJPEGRepresentation(imageView.image!, 1)


let base64String = (imageData! as Data).base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
print(base64String)

斯威夫特3.0

将图像转换为base64字符串

操场测试

    var logo = UIImage(named: "image_logo")
let imageData:Data =  UIImagePNGRepresentation(logo)
let base64String = imageData.base64EncodedString()
print(base64String)

4.2扩展方法

extension UIImage {
func toBase64() -> String? {
guard let imageData = self.pngData() else { return nil }
return imageData.base64EncodedString(options: .lineLength64Characters)
}
}

XCode 9.1和Swift 4.0

//
// Convert UIImage to a base64 representation
//
class func convertImageToBase64(image: UIImage) -> String {
let imageData = UIImagePNGRepresentation(image)!
return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
}


//
// Convert a base64 representation to a UIImage
//
class func convertBase64ToImage(imageString: String) -> UIImage {
let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
return UIImage(data: imageData)!
}

斯威夫特5

编码

func convertImageToBase64String (img: UIImage) -> String {
return img.jpegData(compressionQuality: 1)?.base64EncodedString() ?? ""
}

解码

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
let imageData = Data(base64Encoded: imageBase64String)
let image = UIImage(data: imageData!)
return image!
}

注意:在xcode 10.2中测试

斯威夫特4

编码

func convertImageToBase64String (img: UIImage) -> String {
let imageData:NSData = UIImageJPEGRepresentation(img, 0.50)! as NSData //UIImagePNGRepresentation(img)
let imgString = imageData.base64EncodedString(options: .init(rawValue: 0))
return imgString
}

解码

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

注意:在xcode 9.4.1中测试

我尝试了所有的解决方案,没有一个对我有效(使用Swift 4),这是对我有效的解决方案,如果将来有人面临同样的问题。

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


yourImage.image = decodedimage

Swift 4.2 | Xcode 10

extension UIImage {


/// EZSE: Returns base64 string
public var base64: String {
return self.jpegData(compressionQuality: 1.0)!.base64EncodedString()
}
}

斯威夫特4

enum ImageFormat {
case png
case jpeg(CGFloat)
}


extension UIImage {
func base64(format: ImageFormat) -> String? {
var imageData: Data?


switch format {
case .png: imageData = UIImagePNGRepresentation(self)
case .jpeg(let compression): imageData = UIImageJPEGRepresentation(self, compression)
}


return imageData?.base64EncodedString()
}
}


extension String {
func imageFromBase64() -> UIImage? {
guard let data = Data(base64Encoded: self) else { return nil }


return UIImage(data: data)
}
}

Swift 5, Xcode 10。

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


print(imageData)

斯威夫特5。

class ImageConverter {


func base64ToImage(_ base64String: String) -> UIImage? {
guard let imageData = Data(base64Encoded: base64String) else { return nil }
return UIImage(data: imageData)
}


func imageToBase64(_ image: UIImage) -> String? {
return image.jpegData(compressionQuality: 1)?.base64EncodedString()
}


}
//convert Image to Base64 (Encoding)


let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)


print(strBase64)


// convert Base64 to Image (Decoding)


let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!


let decodedimage:UIImage = UIImage(data: dataDecoded)!


print(decodedimage)


yourImageView.image = decodedimage

对于Base64代码,例如:

“数据:图像/ jpg, base64 iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAAB9klEQVR42u2YQYorMQxEBbqWQFc36FoG / 6 pyopnz / J20mGGaTiftF2hbLpWU2PnfYX / k55Jl5vhUVTu8luUdaCeFcydejjdwDUyQ5XV2JOcSZnkHZgiejusK51QGycrl2yIR1BwjjKivSFz8YC7fY91GKIj6PL5pp4 / wWL54t3MHt / AjFxoJwmkYwosbh6 UEHE817hvi / vGex8gEkTdVRo1/55BM7kjUIgpoMW1DxB6kD + GtCX4PUFws40OwcUm0 / lRYjOB3pG9YcguBFQuO0ISJ9UIrUP5CKy / MriXHDkETYmLDax1 + RkgWBglQgUyq6T / HCAHBq7iJHd9KWWAlIKoGpiLc6HNDhDkETNYwqeVhym72snKKxA6BJL4UPM5QPYtgGwZeNZ5O0UvgSb0VGdcmVfJCQwQrM + pRiGnYJ497SUlv2NOYfOCX3qU2Equ7W3JAslsN7oDBDWWojcZq + KbEwQRdRYl1wD3ML52rpGc6w24qCXaKh4DRHWJbUPemqtEGyBMKC4Q / QmWiDWzRxkgO1UtSLh3svMaILeDpEGwrwvZ4Bkg9LynK1Y1LJWQdqKGnm3K7VTCz7vS9hIuUyYRd / xKcYRIHGqAViisQ4S / Uozmqo41Pn6bNRI1xS / fk2fMEKpDZYkpjP6B1T0HyN9 / Nb + M / AORXDdE4Lb / mQAAAABJRU5ErkJggg = =“

使用Swift5.0代码如下:

func imageFromBase64(_ base64: String) -> UIImage? {
if let url = URL(string: base64), let data = try? Data(contentsOf: url) {
return UIImage(data: data)
}
return nil
}
这是一个很好的理解你传递前缀作为泰勒犀飞利告诉。 但由于某些原因,您可能需要在base64字符串的开头使用这个描述mime-type的前缀,因此我建议这段代码在编码(斯威夫特5)之前传递一些选项:

extension UIImage {


enum Format: String {
case png = "png"
case jpeg = "jpeg"
}


func toBase64(type: Format = .jpeg, quality: CGFloat = 1, addMimePrefix: Bool = false) -> String? {
let imageData: Data?
switch type {
case .jpeg: imageData = jpegData(compressionQuality: quality)
case .png:  imageData = pngData()
}
guard let data = imageData else { return nil }


let base64 = data.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)


var result = base64
if addMimePrefix {
let prefix = "data:image/\(type.rawValue);base64,"
result = prefix + base64
}
return result
}
}

解码使用方便的初始化器- Swift 5

extension UIImage {
convenience init?(base64String: String) {
guard let data = Data(base64Encoded: base64String) else { return nil }
self.init(data: data)
}
}