Swift 影象轉換為Base64字串

weixin_34402408發表於2016-03-06
//本地路徑檔案
let filePath = NSBundle.mainBundle().pathForResource("test", ofType: "jpg")
let data = NSData(contentsOfFile: filePath!)
let base64 = data!.base64EncodedStringWithOptions(.EncodingEndLineWithLineFeed)

//使用影象名稱建立NSData
let image = UIImage(named:"imageNameHere")!
let imageData = UIImagePNGRepresentation(image)
let base64 = imageData!.base64EncodedStringWithOptions(.EncodingEndLineWithCarriageReturn)

//建立NSData使用影象的路徑
let url = NSURL(string : "urlHere")!
let imageData = NSData(contentsOfURL: url)

//Swift 2.0 Encoding(編碼)
let base64String = imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

//Swift 2.0 Decoding(解碼)
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)

相關文章