base64编码要上传的图像

base64编码要上传的图像

本文介绍了Swift 3 base64编码要上传的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些不错的代码,可让我进行图片和图像处理,然后在应用程序中显示.我也将profilePic.image上传到我的数据库(作为Blob),但是我意识到这实际上不是在上传图像本身,而只是在上传有关图像的数据,因此我无法将任何内容渲染回去,因为没有可解码的内容.因此,我想转换此功能以获取所选的图像并将其编码为base64并利用相同的工作上传

I have some nice code that allows me to pic and image and then display it in app. I was also uploading the profilePic.image to my database (as a blob) but I realised that this was not actually uploading the image itself but just data about the image so I could not render anything back as there was nothing to decode. So I want to transform this function to get the chosen image and encode it to base64 and utilise same working upload

func imagePickerController(
        _ selectImage: UIImagePickerController,
        didFinishPickingMediaWithInfo info: [String : AnyObject])
    {
        let chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage //2
        // imageByCroppingToRect()
        profilePic.contentMode = .scaleAspectFit //3
        profilePic.image = chosenImage //4
        dismiss(animated: true, completion: nil) //5
    }

推荐答案

您必须将UIImage转换为网站可以读取的格式,例如jpeg,然后在base 64中进行编码.

You have to convert the UIImage to a format your website can read, e.g. jpeg before encoding it in base 64.

let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = UIImageJPEGRepresentation(chosenImage, jpegCompressionQuality)?.base64EncodedString() {
    // Upload base64String to your database
}

注意:在iOS 12中,UIImageJPEGRepresentation已替换为UIImage的实例方法jpegData:

Note: In iOS 12 UIImageJPEGRepresentation was replaced by an instance method jpegData of UIImage:

let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = chosenImage.jpegData(compressionQuality: jpegCompressionQuality)?.base64EncodedString() {
    // Upload base64String to your database
}

有关 UIImageJPEGRepresentation 数据

这篇关于Swift 3 base64编码要上传的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 08:40