2016-09-11 112 views
2

我有一些不錯的代碼,允許我照片和圖像,然後在應用程序中顯示它。我還將profilePic.image上傳到我的數據庫(作爲blob),但我意識到這實際上並沒有上傳圖像本身,而只是關於圖像的數據,所以我無法渲染任何東西,因爲沒有任何東西需要解碼。所以我想要改造這個函數來獲得所選擇的圖像,並將其編碼爲Base64和使用相同的工作上傳Swift 3 base64編碼圖像上傳

func imagePickerController(
     _ selectImage: UIImagePickerController, 
     didFinishPickingMediaWithInfo info: [String : AnyObject]) 
    { 
     let chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage //2 
     // imageByCroppingToRect() 
     profilePic.contentMode = .scaleAspectFit //3 
     profilePic.image = chosenImage //4 
     dismiss(animated: true, completion: nil) //5 
    } 

回答

9

你必須在UIImage轉換爲格式的網站可以讀取,例如在基礎編碼之前JPEG 64

let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose 
if let base64String = UIImageJPEGRepresentation(chosenImage, jpegCompressionQuality)?.base64EncodedString() { 
    // Upload base64String to your database 
} 

請參考蘋果文檔UIImageJPEGRepresentationData