gpt4 book ai didi

ios - 如何在 swift 4 中减小照片大小并在参数中发送到我的服务器

转载 作者:行者123 更新时间:2023-11-28 05:55:31 25 4
gpt4 key购买 nike

我正在使用 UIImagePickerController 拍照并将图像转换为 base64,我想将图像发送到我的服务器,但照片正在转换为 base64,但问题是我无法发送转换后的照片在参数中发送到我的服务器

这里是我的代码

@IBOutlet weak var CameraOutlet: UIButton!
@IBOutlet weak var Complaint_Image1: UIImageView!
@IBOutlet weak var Complaint_Image2: UIImageView!
@IBOutlet weak var Complaint_Image3: UIImageView!


func TakePhotos() {
let Image = UIImagePickerController()
Image.allowsEditing = true
Image.sourceType = UIImagePickerControllerSourceType.camera
Image.delegate = self

present(Image, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let picture = info[UIImagePickerControllerOriginalImage] as? UIImage {

if (Complaint_Image1.image != nil && Complaint_Image2.image != nil) {
Complaint_Image3.image = picture
}
else if Complaint_Image1.image != nil {
Complaint_Image2.image = picture
}
else {
Complaint_Image1.image = picture
}
}

if Complaint_Image1.image != nil {
let imageData:NSData = UIImagePNGRepresentation(Complaint_Image1.image!)! as NSData
let imageStr = imageData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let imageBase64 = imageStr
let imgstr2 = String.init(format: "data:image/png;base64,%@", imageBase64)

UserDefaults.standard.set(imgstr2, forKey: "image")
UserDefaults.standard.synchronize()
}

let picture1 = UserDefaults.standard.object(forKey: "image")
let parameter = ["Image1": picture1!,"Image":[["name": picture2],["name": picture3]] as [String: Any]
}

最佳答案

在上传到服务器端之前,只需使用以下代码压缩图像

首先,将 uiimage 的以下扩展添加到任何类或单例类

extension UIImage {

//MARK:- convenience function in UIImage extension to resize a given image
func convert(toSize size:CGSize, scale:CGFloat) ->UIImage {
let imgRect = CGRect(origin: CGPoint(x:0.0, y:0.0), size: size)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
self.draw(in: imgRect)
let copied = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

return copied!
}
}

然后在选择图像的 Controller 中编写以下方法

//MARK:- ImagePicker Delegate Methods

internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// resize our selected image
let resizedImage = chosenImage.convert(toSize:CGSize(width:100.0, height:100.0), scale: UIScreen.main.scale)
profileImg.image = resizedImage
dismiss(animated:true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}

关于ios - 如何在 swift 4 中减小照片大小并在参数中发送到我的服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51589672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com