Converting Image to BASE64 String in swift

2019-02-17 13:23发布

I am trying to convert the Image which is picked by user either from his Photos or Take New from Camera. I am able to convert the image into base64 string but the problem is that it takes too much time and prints a long infinite string

Here is the output of String which i am getting

enter image description here

here is my code:

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


    }

3条回答
Rolldiameter
2楼-- · 2019-02-17 13:40

Make sure your image extension first.

// .png

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

// .JPEG

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

// BASE 64

  imageData.base64EncodedString()
查看更多
时光不老,我们不散
3楼-- · 2019-02-17 13:43

Actually it is not taking time to convert(very less time) for printing it will take more time so don't print it....

查看更多
叼着烟拽天下
4楼-- · 2019-02-17 13:44

You can apply this code

let imageData: Data? = UIImageJPEGRepresentation(getImage(), 0.4)
let imageStr = imageData?.base64EncodedString(options: .lineLength64Characters) ?? ""
print(strBase64)
查看更多
登录 后发表回答