在UIImage和Base64字符串之间转换


224

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

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

NSData *imageData = UIImagePNGRepresentation(viewImage);

NSString *b64EncStr = [self encode: imageData];

NSString *base64String = [self encodeBase64:imageData];


任何人都可以回答这个问题:stackoverflow.com/questions/39657434/...
user3011809

Answers:


575

迅速

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

物镜

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图像

在您的中添加Base64project

编码方式

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

解码

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

另一个选择:将QSUtilities用于encodingdecoding



1
@Safecase我不是投票否决您的人,但可能双重职务是犯罪?
Tommy 2012年

1
不是,但是我想对这个问题给出正确的答案
Paresh Navadiya 2012年

2
Base64课堂永远睡着,即使在使图像质量达到0.001f之后,即使使用xcode,我也总是会强制使用xcode
shebelaw 2013年

6
重要说明:请确保您的base64字符串不包含浏览器上显示所需的前缀,例如data:image/jpeg;base64,
Tyler Sheaffer

2
@TylerSheaffer我认为这是一条重要消息,应将其包含在答案中。
永恒的

33

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)!
}

19

SWIFT 3.0,XCODE 8.0

将URL替换为您的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

希望对您有所帮助。


19

迅捷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中测试


感谢您对我的回答发表评论,请您对我的答案进行投票,这对我很有帮助。
Vivek

11

斯威夫特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

8

斯威夫特3.0

将图像转换为base64字符串

在操场上测试

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

7
@implementation UIImage (Extended)

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

@end

1
简洁大方。爱它!
Myxtic 2014年

7

在Swift 2.0中,请使用此扩展名(提供给Jonas Franz)

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

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

4

快速扩展:

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

对于Swift 2.2,.allZeros不会编译。所以我用return imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue:0))
卡尔·史密斯

使用Encoding64CharacterLineLength代替allZero
Jonas Franz

1
即时通讯使用switft3,无法转换以发送到服务器:let imageData = UIImagePNGRepresentation(ImageView.image!); let strBase64:String = imageData!.base64EncodedString()
Cmag

@Cmag我知道您的评论已经2岁了,但是您设法解决了吗?

@ZUNJAE恐怕我不记得我是如何解决它的,不再有使用该解决方案的机会
Cmag

3

斯威夫特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)
    }
}

3

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

}

2

Swift版本-为图像创建base64

我认为,在UIImagePNGRepresenatation()不安全的情况下隐式展开Optional 是不安全的,因此我建议使用如下扩展名:

extension UIImage {

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

1
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)
    }
}

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!

}

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

我还尝试了许多解决方案,该解决方案可节省我的下几个小时
艾哈迈德(Ahmad)



1
//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

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];

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)

0

对于类似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 qrcodeImage(_ base64: String) -> UIImage? {
    if let url = URL(string: base64) {
        if let data = try? Data(contentsOf: url) {
            return UIImage(data: data)
        }
    }
    return nil
}

0

Tyler Sheaffer所说,很高兴了解您是否传递前缀。但是出于某种原因,您可能需要在base64字符串开头描述此mime类型的前缀,因此我建议这段代码在编码之前先传递一些选项(Swift 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
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.