有人知道如何将一个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 2.0中使用此扩展(credit to Jonas Franz)
extension UIImage{
func toBase64() -> String{
let imageData = UIImagePNGRepresentation(self)!
return imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
}
}
其他回答
斯威夫特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 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()
}
}
斯威夫特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()
}
}
对于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];