首先需要实现UIImagePickerControllerDelegate 代理 实现其imagePickerController 方法 这里用于选择图片或的拍照回调
//调用相机拍照 或者 图库选择 let picker = UIImagePickerController() picker.sourceType = .camera //图库 .photoLibrary picker.delegate = self picker.allowsEditing = true //开启图片编辑裁剪 会有正方形的选框显示 UIApplication.shared.keyWindow?.rootViewController?.present(picker, animated: true, completion: nil) //图片回调方法 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { // 获取选择的裁剪后的图片 fixOrientation 处理旋转不正常问题 并压缩到300*300 let pickedImage = (info[UIImagePickerController.InfoKey.editedImage] as! UIImage).fixOrientation().scaleToSize(size: CGSize( 300, height: 300)) // 是否支持相册 if UIImagePickerController.isValidImagePickerType(type: UIImagePickerType.UIImagePickerTypePhotoLibrary) { // 相册 } else if (UIImagePickerController.isValidImagePickerType(type: UIImagePickerType.UIImagePickerTypeCamera)){ // 相机 // 图片保存到相册 UIImageWriteToSavedPhotosAlbum(pickedImage, self, Selector(("imageSave:error:contextInfo:")), nil) } //这里是个回调结构体 在使用的地方实现这个结构体即可获取到处理好的图片 if self.selectedImageBlock != nil { self.selectedImageBlock!(pickedImage) } picker.dismiss(animated: true) { } } //取消图片选择框 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) }
相关定义的方法
extension UIImage { /// 修复图⽚旋转 func fixOrientation() -> UIImage { if self.imageOrientation == .up { return self } var transform = CGAffineTransform.identity switch self.imageOrientation { case .down, .downMirrored: transform = transform.translatedBy(x: self.size.width, y: self.size.height) transform = transform.rotated(by: .pi) break case .left, .leftMirrored: transform = transform.translatedBy(x: self.size.width, y: 0) transform = transform.rotated(by: .pi / 2) break case .right, .rightMirrored: transform = transform.translatedBy(x: 0, y: self.size.height) transform = transform.rotated(by: -.pi / 2) break default: break } switch self.imageOrientation { case .upMirrored, .downMirrored: transform = transform.translatedBy(x: self.size.width, y: 0) transform = transform.scaledBy(x: -1, y: 1) break case .leftMirrored, .rightMirrored: transform = transform.translatedBy(x: self.size.height, y: 0); transform = transform.scaledBy(x: -1, y: 1) break default: break } let ctx = CGContext(data: nil, Int(self.size.width), height: Int(self.size.height), bitsPerComponent: self.cgImage!.bitsPerComponent, bytesPerRow: 0, space: self.cgImage!.colorSpace!, bitmapInfo: self.cgImage!.bitmapInfo.rawValue) ctx?.concatenate(transform) switch self.imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: ctx?.draw(self.cgImage!, in: CGRect(x: CGFloat(0), y: CGFloat(0), CGFloat(size.height), height: CGFloat(size.width))) break default: ctx?.draw(self.cgImage!, in: CGRect(x: CGFloat(0), y: CGFloat(0), CGFloat(size.width), height: CGFloat(size.height))) break } let cgimg: CGImage = (ctx?.makeImage())! let img = UIImage(cgImage: cgimg) return img } //将图⽚裁剪成指定⽐例(多余部分⾃动删除) func crop(ratio: CGFloat) -> UIImage { //计算最终尺⼨ var newSize:CGSize! if size.width/size.height > ratio { newSize = CGSize( size.height * ratio, height: size.height) }else{ newSize = CGSize( size.width, height: size.width / ratio) } ////图⽚绘制区域 var rect = CGRect.zero rect.size.width = size.width rect.size.height = size.height rect.origin.x = (newSize.width - size.width ) / 2.0 rect.origin.y = (newSize.height - size.height ) / 2.0 //绘制并获取最终图⽚ UIGraphicsBeginImageContext(newSize) draw(in: rect) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage! } //压缩图⽚宽⾼ func scaleToSize(size:CGSize) -> UIImage{ UIGraphicsBeginImageContext(size) self.draw(in: CGRect(x: 0, y: 0, size.width, height: size.height)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage! } } // 相机相关扩展类⽅法 import UIKit import Photos /// 相⽚选择器类型:相册 PhotoLibrary,图库 SavedPhotosAlbum,相机Camera,前置摄像头 Front,后置摄像头 Rear public enum UIImagePickerType:Int { /// 相册 PhotoLibrary case UIImagePickerTypePhotoLibrary = 1 /// 图库 SavedPhotosAlbum case UIImagePickerTypeSavedPhotosAlbum = 2 /// 相机 Camera case UIImagePickerTypeCamera = 3 /// 前置摄像头 Front case UIImagePickerTypeCameraFront = 4 /// 后置摄像头 Rear case UIImagePickerTypeCameraRear = 5 } extension UIImagePickerController { // MARK: - 设备使⽤有效性判断 // 相册 PhotoLibrary,图库 SavedPhotosAlbum,相机 Camera,前置摄像头Front,后置摄像头 Rear public class func isValidImagePickerType(type imagePickerType:UIImagePickerType) -> Bool { switch imagePickerType { case .UIImagePickerTypePhotoLibrary: if self.isValidPhotoLibrary { return true } return false case .UIImagePickerTypeSavedPhotosAlbum: if self.isValidSavedPhotosAlbum { return true } return false case .UIImagePickerTypeCamera: if self.isValidCameraEnable && self.isValidCamera { return true } return false case .UIImagePickerTypeCameraFront: if self.isValidCameraEnable && self.isValidCameraFront { return true } return false case .UIImagePickerTypeCameraRear: if self.isValidCamera && self.isValidCameraRear { return true } return false } } /// 相机设备是否启⽤ public class var isValidCameraEnable:Bool{ get { let cameraStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio) if cameraStatus == AVAuthorizationStatus.denied { return false } return true } } /// 相机Camera是否可⽤(是否有摄像头) public class var isValidCamera:Bool{ get { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.Sourc eType.camera){ return true } return false } } /// 前置相机是否可⽤ public class var isValidCameraFront:Bool{ get { if UIImagePickerController.isCameraDeviceAvailable(UIImagePickerController.Ca meraDevice.front){ return true } return false } } /// 后置相机是否可⽤ public class var isValidCameraRear:Bool{ get { if UIImagePickerController.isCameraDeviceAvailable(UIImagePickerController.Ca meraDevice.rear){ return true } return false } } /// 相册PhotoLibrary是否可⽤ public class var isValidPhotoLibrary:Bool{ get { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.Sourc eType.photoLibrary) { return true } return false } } /// 图库SavedPhotosAlbum是否可⽤ public class var isValidSavedPhotosAlbum:Bool { get { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.Sourc eType.savedPhotosAlbum) { return true } return false } } // MARK: - 属性设置 func setImagePickerStyle(bgroundColor:UIColor?, titleColor:UIColor?, buttonTitleColor:UIColor?) { // 改navigationBar背景⾊ if let bgroundColor:UIColor = bgroundColor { self.navigationBar.barTintColor = bgroundColor } // 改navigationBar标题⾊ if let titleColor:UIColor = titleColor { self.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor] } // 改navigationBar的button字体⾊ if let buttonTitleColor:UIColor = buttonTitleColor { self.navigationBar.tintColor = buttonTitleColor } } }
//拿到图片后我们使用ALamofire上传
//url 上传url地址 //image 需要上传的uiimage //execute 回调函数 func upload(_ url:String,image:UIImage,execute:@escaping (Int,JSON) -> Void){ let headers:HTTPHeaders = [ "headerkey": "headerVal", ] //Alamofire.upload(image.jpegData(compressionQuality: 0.5)!, to: url) Alamofire.upload(multipartFormData: {(data) in data.append(image.jpegData(compressionQuality: 0.6)!, withName: "file",fileName: "(Date().timeIntervalSince1970).jpg",mimeType: "image/jpeg") },to: url as URLConvertible,method: .post,headers: headers, encodingCompletion: {(result) in switch result{ case .success(let upload,_,_): upload.responseJSON{response in guard let result = response.result.value else { return } print("json:(result)") let json = JSON(result) execute(json["code"].intValue,,nil) } break case .failure(let err): print(err) execute(-1,nil) break } print(result) }) }