嗨我想将图像转换为数据,但问题是数据将返回nil 我想用Alamofire上传图片所以我需要在使用Alamofire之前转换图像这里是我的代码
let imageData = UIImageJPEGRepresentation(ViewController.imageUpload[i], 1.0)
Alamofire.upload(imageData! , to: "http://example.com/api/file?api_token=\(api_token)&id=\(postID)").responseJSON { response in
debugPrint(response)
}
答案 0 :(得分:2)
尝试下面的代码来获取imageData,并确保你传递的图像不是nil,
对于PNG: -
let data = UIImagePNGRepresentation(ViewController.imageUpload[i]) as NSData?
对于JPEG: -
let data = UIImageJPEGRepresentation(ViewController.imageUpload[i], 1.0) as NSData?
并且还要在保存时检查您正在使用的图像扩展名(PNG或JPEG)
要了解图片扩展程序,请查看以下代码,
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if (!(picker.sourceType == UIImagePickerControllerSourceType.Camera)) {
let assetPath = info[UIImagePickerControllerReferenceURL] as! NSURL
if assetPath.absoluteString.hasSuffix("JPG") {
}
}
}