有人知道如何将一个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 4),这是对我有效的解决方案,如果将来有人面临同样的问题。
let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options:
.ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImage.image = decodedimage
其他回答
在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版本-创建base64镜像
在我看来,在UIImagePNGRepresenatation()的情况下隐式Unwrapped Optional是不安全的,所以我建议使用扩展如下:
extension UIImage {
func toBase64() -> String? {
let imageData = UIImagePNGRepresentation(self)
return imageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
}
}
斯威夫特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)
}
}
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。
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()
}
}