迅速
まず、画像の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
Objective-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
とdecode
画像を使用
にBase64クラスを追加しますproject
。
エンコーディング:
NSData* data = UIImageJPEGRepresentation(yourImage, 1.0f);
NSString *strEncoded = [Base64 encode:data];
デコード:
NSData* data = [Base64 decode:strEncoded ];;
image.image = [UIImage imageWithData:data];
別のオプション:およびにQSUtilitiesを使用するencoding
decoding