在swift中将图像转换为BASE64字符串

时间:2016-12-06 06:27:13

标签: ios swift2 uiimage base64 nsdata

我正在尝试转换用户从他的照片中挑选的图像或从相机拍摄新照片。我能够将图像转换为base64字符串,但问题是它需要花费太多时间并打印一个长的无限字符串

这是我得到的String的输出

enter image description here

这是我的代码:

// Image picker from Gallery
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imagePicker.dismissViewControllerAnimated(true, completion: nil)
        profileImage.image = image

    }

    // Image Picker from Camera

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        imagePicker.dismissViewControllerAnimated(true, completion: nil)
        profileImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage

        addPicBtn.setImage(nil, forState: .Normal)

        let imageData:NSData = UIImagePNGRepresentation(profileImage.image!)!
        let imageStr = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
        print(imageStr)


    }

5 个答案:

答案 0 :(得分:9)

实际上没有时间进行转换(非常少的时间)进行打印需要更多时间,所以不要打印....

答案 1 :(得分:9)

您可以应用此代码

let imageData: Data? = UIImageJPEGRepresentation(getImage(), 0.4)
let imageStr = imageData?.base64EncodedString(options: .lineLength64Characters) ?? ""
print(strBase64)

答案 2 :(得分:1)

请先确保您的图片扩展名。

// .png

    guard let imageData = UIImagePNGRepresentation(UIImage) else {
        return ""
    }

// .JPEG

   guard let imageData = UIImageJPEGRepresentation(UIImage, 1) else {
                return ""
    }

// BASE 64

  imageData.base64EncodedString()

答案 3 :(得分:1)

Swift 4版本。这个简单的功能对我来说效果很好。使用以下命令确认返回的解码图像:https://codebeautify.org/base64-to-image-converter 希望这对某人有帮助。

public static func  convertImageToBase64String(image : UIImage ) -> String 
{
    let strBase64 =  image.pngData()?.base64EncodedString()
    return strBase64!
}

答案 4 :(得分:0)

let imageData: Data? = UIImageJPEGRepresentation(YourImage, 0.4)
let imageStr = imageData?.base64EncodedString(options: .lineLength64Characters) ?? ""
print(imageStr,"imageString")

After printing imageStr you will huge output like in this attached image below, it means you are done successfully.