ios uiimagepickercontroller 选择相册或者拍照上传
首先需要实现UIImagePickerControllerDelegate 代理 实现其imagePickerController 方法 这里用于选择图片或的拍照回调
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //调用相机拍照 或者 图库选择 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 ( width : 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 ) } |
相关定义的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | 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 , width : 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 ), width : CGFloat ( size . height ), height : CGFloat ( size . width ))) break default : ctx ?. draw ( self . cgImage !, in : CGRect ( x : CGFloat ( 0 ), y : CGFloat ( 0 ), width : 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 ( width : size . height * ratio , height : size . height ) } else { newSize = CGSize ( width : 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 , width : 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上传
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | //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 ) }) } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· 程序员常用高效实用工具推荐,办公效率提升利器!
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 【译】WinForms:分析一下(我用 Visual Basic 写的)
2018-12-07 element-ui + el-dialog + Vue.component 注册的tinymce富文本控件 第二次及以后打开dialog出现问题解决方法