Convert base64 image to StringIO for Carrierwave

后端 未结 2 509
眼角桃花
眼角桃花 2021-02-04 20:33

I am hoping someone can help me understand this. I have a base64 string for an image:

\"data:image/jpeg;base64,/9j/4AAQSkZJRgABA...\"

I would

相关标签:
2条回答
  • 2021-02-04 20:37

    And yes that string does need to be broken up:

    var data = newImage.split(',');  
    this.get('store').createRecord(Emb.Painting, {name: newName, image: data[1]});  
    

    I doubt this is the best way...

    0 讨论(0)
  • 2021-02-04 21:03

    Yes, you need to split the string. You could use something like this:

    def splitBase64(uri)
      if uri.match(%r{^data:(.*?);(.*?),(.*)$})
        return {
          type:      $1, # "image/png"
          encoder:   $2, # "base64"
          data:      $3, # data string
          extension: $1.split('/')[1] # "png"
          }
      end
    end
    

    Then you can decode the image...

    base64image = params[:painting][:image]
    imageDataString = splitBase64(base64image)[:data]
    imageDataBinary = Base64.decode64(imageDataString)
    

    Then you can pass the imageDataBinary to StringIO.new() and the resulting image should be valid.

    0 讨论(0)
提交回复
热议问题