ios uiimagepickercontroller 選擇相冊或者拍照上傳


首先需要實現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(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)
    }

  相關定義的方法

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上傳

//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)
        })
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM