base64转换图像StringIO的为Carrierwave

base64转换图像StringIO的为Carrierwave

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

问题描述

我希望有人能帮助我理解这一点。我有一个像一个base64字符串:

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

我想使用Ember的createRecord向它发送和提交():

I would like to send it using ember's createRecord and commit():

this.get('store').createRecord(Emb.Painting, {name: newName, image: newImage});

然后我想将其转换为StringIO的为carrierwave并保存:

Then I want to convert it to StringIO for carrierwave and save it:

StringIO.class_eval { def original_filename; "stringiohaxx.jpg"; end }
io = StringIO.new(Base64.decode64(params[:painting][:image]))
@painting =  Painting.create(:name => params[:painting][:name], :image => io )

这是图像被保存。图像总是损坏。我需要打破我打破我的base64串入:

An image is saved. The image is always corrupted. Do I need to break my break my base64 string into:

data: '/9j/..'
type: 'image/jpeg'

?任何帮助AP preciated。

? Any help appreciated.

推荐答案

是的,你需要分割字符串。你可以使用这样的:

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

然后你可以去code图像...

Then you can decode the image...

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

然后就可以通过imageDataBinary到StringIO.new()和生成的图像应该是有效的。

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

这篇关于base64转换图像StringIO的为Carrierwave的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 21:52