有人知道如何将一个UIImage转换为Base64字符串,然后反转它吗?
我有以下代码;编码前的原始图像是好的,但编码解码后只得到一个空白图像。
NSData *imageData = UIImagePNGRepresentation(viewImage);
NSString *b64EncStr = [self encode: imageData];
NSString *base64String = [self encodeBase64:imageData];
有人知道如何将一个UIImage转换为Base64字符串,然后反转它吗?
我有以下代码;编码前的原始图像是好的,但编码解码后只得到一个空白图像。
NSData *imageData = UIImagePNGRepresentation(viewImage);
NSString *b64EncStr = [self encode: imageData];
NSString *base64String = [self encodeBase64:imageData];
当前回答
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)
其他回答
Swift版本-创建base64镜像
在我看来,在UIImagePNGRepresenatation()的情况下隐式Unwrapped Optional是不安全的,所以我建议使用扩展如下:
extension UIImage {
func toBase64() -> String? {
let imageData = UIImagePNGRepresentation(self)
return imageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
}
}
在swift 2.0中使用此扩展(credit to Jonas Franz)
extension UIImage{
func toBase64() -> String{
let imageData = UIImagePNGRepresentation(self)!
return imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
}
}
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)!
}
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-Extension:
extension UIImage{
func toBase64() -> String{
var imageData = UIImagePNGRepresentation(self)
return imageData.base64EncodedStringWithOptions(.allZeros)
}
}