快速从 imageView.image 创建 jpeg 图像

Posted

技术标签:

【中文标题】快速从 imageView.image 创建 jpeg 图像【英文标题】:Create jpeg image from imageView.image in swift 【发布时间】:2020-10-26 09:02:55 【问题描述】:

我正在开发一个用户必须注册的应用程序。在此过程中,您可以选择个人资料图像。这个过程是这样的:你点击imageViewimagePicker打开(你可以从相机或图库中选择),在你选择一个图像后,picker关闭并且图像被加载到imageview .现在的问题是,如何从imageView.image 创建一个jpeg,以便我可以通过Alamofire 将其上传到后端?

这里是代码:

当通过选择器选择图像时:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) 
    if let pickedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage 
        //previewImage is the imageView where the image is displayed
        previewImage.image = pickedImage
        previewImage.layer.cornerRadius = 55
        profileView.translatesAutoresizingMaskIntoConstraints = false
        profileImageView.isHidden = true
    

        UserData.shared.profilePicture = previewImage.image!
    
    dismiss(animated: true, completion: nil)

这里是上传图片的方法:

    func uploadImage(profileImage: UIImage) 
    
    let image = profileImage.jpegData(compressionQuality: 0.5)
    let filename = getDocumentsDirectory().appendingPathComponent("profile.jpeg")
    try? image!.write(to: filename)
    
    
    AF.request(Constants.uploadProfileUrl, method: .post, parameters: ["profile": UIImage(named: "profile")], headers: ["Content-Type":"multipart/form-data", "Authorization": "Bearer "+Configuration.accessToken])  urlRequest in
    .response  response in
        print(response)
        switch response.result 
        case .success:
            self.performSegue(withIdentifier: Constants.successfulRegister, sender: self)
        case .failure(let error):
            let statusCode = response.response?.statusCode
            print(statusCode)
            print("fail")
        
    

不知何故,我从alamofire 收到了一条成功消息,但图片未显示在后端。

【问题讨论】:

【参考方案1】:

试试看:-

为 UIImage 取一个全局变量 将选取的图像存储在该变量中 在 alamofire 中发送该图像(如果需要,请压缩)
let image = UIImage()

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) 
    if let pickedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage 
        self.image = pickedImage
        previewImage.image = pickedImage
        previewImage.layer.cornerRadius = 55
        profileView.translatesAutoresizingMaskIntoConstraints = false
        profileImageView.isHidden = true
    

        UserData.shared.profilePicture = previewImage.image!
    
    dismiss(animated: true, completion: nil)

【讨论】:

以上是关于快速从 imageView.image 创建 jpeg 图像的主要内容,如果未能解决你的问题,请参考以下文章

快速旋转 UIImage

通过 HTTP $_POST 快速上传图片

我是不是通过显式处理 imageView.Image 来赢得内存?

UITableViewCell.ImageView.image 比较 UIImage

iOS如何固定UITableView中cell.imageView.image的图片大小

如何从数组中获取特定图像?