在UIImage和Base64字符串之间转换

时间:2012-06-28 19:11:10

标签: ios swift uiimage base64 nsdata

有谁知道如何将UIImage转换为Base64字符串,然后将其反转?

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

NSData *imageData = UIImagePNGRepresentation(viewImage);

NSString *b64EncStr = [self encode: imageData];

NSString *base64String = [self encodeBase64:imageData];

24 个答案:

答案 0 :(得分:541)

夫特

首先我们需要拥有图片的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

Swift 3.0

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

目标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和<版本

第一个选项:使用encode链接到decodeproject图片

NSData* data = UIImageJPEGRepresentation(yourImage, 1.0f); NSString *strEncoded = [Base64 encode:data]; 中添加this课程。

编码

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

解码

encoding

另一个选项decoding使用Base64和{{1}}


答案 1 :(得分:23)

Swift 4.2扩展方法

extension UIImage {
    func toBase64() -> String? {
        guard let imageData = self.pngData() else { return nil }
        return imageData.base64EncodedString(options: Data.Base64EncodingOptions.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)!
}

答案 2 :(得分:19)

SWIFT 3.0,XCODE 8.0

用您的URL替换String。和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

希望它能帮助你。

答案 3 :(得分:11)

Swift 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

答案 4 :(得分:8)

Swift 3.0

将图片转换为base64字符串

在游乐场测试

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

答案 5 :(得分:7)

@implementation UIImage (Extended)

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

@end

答案 6 :(得分:6)

在swift 2.0中使用此扩展程序(归功于Jonas Franz)

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

答案 7 :(得分:5)

在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

答案 8 :(得分:5)

雨燕5

编码

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

解码

func ConvertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0))
    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中测试

答案 9 :(得分:4)

夫特 - 分机:

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

答案 10 :(得分:2)

迅速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()
    }

}

答案 11 :(得分:2)

快捷键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)
    }
}

答案 12 :(得分:1)

Swift版本 - 为图片创建base64

在我看来隐式解包在UIImagePNGRepresenatation()的情况下可选择不安全,所以我建议使用如下的扩展程序:

extension UIImage {

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

答案 13 :(得分:1)

对于Base64代码,例如:

“数据:图像/ JPG; BASE64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAAB9klEQVR42u2YQYorMQxEBbqWQFc36FoG / 6pyOpNZ / 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) {
        if let data = try? Data(contentsOf: url) {
            return UIImage(data: data)
        }
    }
    return nil
}

答案 14 :(得分:1)

Swift 4.2 | Xcode 10

extension UIImage {

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

答案 15 :(得分: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

答案 16 :(得分:1)

在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!

}

答案 17 :(得分:1)

{{1}}

答案 18 :(得分:0)

对于iOS 7 +,Objective-C,以下是如何从图片网址开始转换:

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

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

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

答案 19 :(得分:0)

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)

答案 20 :(得分:0)

Swift 4.2,Xcode 10.1

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

print(imageData)

答案 21 :(得分:0)

//将图像转换为Base64(编码)

let strBase64 = imageData.base64EncodedString(选项:.lineLength64Characters)

print(strBase64)

///将Base64转换为图像(解码)

让dataDecoded:NSData = NSData(base64EncodedString:strBase64,选项:NSDataBase64DecodingOptions(rawValue:0))!

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

打印(解码图像)

yourImageView.image =解码图像

答案 22 :(得分:0)

很高兴了解您是否按照 Tyler Sheaffer 的说明传递前缀。 但是出于某些原因,您可能需要在base64字符串开头描述该mime类型的前缀,因此,我建议这段代码在编码之前先传递一些选项( Swift 5 ):

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
    at org.example.ReadCSV.getOneCsv(ReadCSV.java:34)
    at org.example.ReadCSV.getCsv(ReadCSV.java:25)
    at org.example.ReadCSV.main(ReadCSV.java:13)"

答案 23 :(得分:0)

使用便捷初始化程序进行解码-Swift 5

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