Util.showGifLoading(self.view) //你的 loading
let imageDataArray = self.lqPhotoPicker_getBigImageDataArray()//这里替换成你的图片 Data 数组
let imageBigArray = self.lqPhotoPicker_getBigImageArray()//这里替换成你的 UIImage 数组
let token:String = UserDefaults.standard.value(forKey: "token") as! String
let url = "your url"
let attachArray:NSMutableArray = NSMutableArray()
for i in 0..<(imageDataArray?.count)! {
//压缩图片
var imgData = imageDataArray?[i] as! Data
let imgBig = imageBigArray?[i] as! UIImage
if(imgData.count/1024 > 100) {
imgData = UIImageJPEGRepresentation(imgBig,0.1)! // 压缩比例在0~1之间,压缩后视觉上不失真
}
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "image", fileName: "file.png", mimeType: "image/png")
},
to: url,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
//以下是根据我们后台返回的数据进行的判断 请自行调整
if let data:NSDictionary = response.result.value as? NSDictionary {
if(Util.processServerError(data)) {
if(data.value(forKey: "retCode") as! String != "0"){
//上传失败提示
Util.showMessage(self.view, text: (data.value(forKey: "message") as! String))
}else{
attachArray.add((data["url"] as? String)!)
self.attach = attachArray.componentsJoined(by: ",")
if(attachArray.count == imageDataArray?.count) {
//上传完成
}
}
}
}else {
Util.showMessage(self.view, text: "图片上传失败,请重试") //你的个性化提示
}
}
case .failure(let encodingError):
print(encodingError)
}
})
}
附:压缩图片尺寸并压缩图片大小
static func zipImage(currentImage: UIImage,scaleSize:CGFloat,percent: CGFloat) -> NSData{
//压缩图片尺寸
UIGraphicsBeginImageContext(CGSizeMake(currentImage.size.width*scaleSize, currentImage.size.height*scaleSize))
currentImage.drawInRect(CGRect(x: 0, y: 0, width: currentImage.size.width*scaleSize, height:currentImage.size.height*scaleSize))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//高保真压缩图片质量
//UIImageJPEGRepresentation此方法可将图片压缩,但是图片质量基本不变,第二个参数即图片质量参数。
let imageData: NSData = UIImageJPEGRepresentation(newImage, percent)!
return imageData
}
网友评论