How to save a base64 string as an image using ruby

前端 未结 4 1037
抹茶落季
抹茶落季 2020-11-29 23:26

I\'m integrating my Ruby on Rails app with a usps shipping system. Once you make a postage request, you pay for that postage and it\'s nonrefundable.

Postage reques

相关标签:
4条回答
  • 2020-11-30 00:05

    When writing binary data to a file, such as is the case with an image, using IO#puts is hazardous and best avoided. You should be writing in binary mode, which is mostly irrelevant on LF-only platforms such as UNIX or OS X, but is imperative on CRLF ones such as Windows. IO#puts also appends a newline at the end of the file which is invalid.

    The best approach is to specify the correct flag on the open call:

    File.open('shipping_label.gif', 'wb') do |f|
      f.write(Base64.decode64(base_64_encoded_data))
    end
    

    For example, see the comment on the IO#open documentation page:

    http://apidock.com/ruby/IO/open/class

    0 讨论(0)
  • 2020-11-30 00:16

    If you need to write it to an image then use imagemagick through the rmagick gem.

    http://rmagick.rubyforge.org/

    0 讨论(0)
  • 2020-11-30 00:17

    Other answers are pretty close, but usually assume that base64 stream will contain PNG data. This is not always the case so I suggest to use mime types library to establish correct file extension:

    REGEXP = /\Adata:([-\w]+\/[-\w\+\.]+)?;base64,(.*)/m
    
    data_uri_parts = data_url.match(REGEXP) || []
    extension = MIME::Types[data_uri_parts[1]].first.preferred_extension
    file_name = "myfilename.#{extension}"
    
    File.open(file_name, 'wb') do |file|
        file.write(Base64.decode64(data_uri_parts[2]))
    end
    
    0 讨论(0)
  • 2020-11-30 00:18
    require 'RMagick'
    data = params[:image_text]# code like this  data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABPUAAAI9CAYAAABSTE0XAAAgAElEQVR4Xuy9SXPjytKm6ZwnUbNyHs7Jc7/VV9bW1WXWi9q
    image_data = Base64.decode64(data['data:image/png;base64,'.length .. -1])
    new_file=File.new("somefilename.png", 'wb')
    new_file.write(image_data)
    

    After you can use image as a file Photo.new(image: image)#save using paperclip in Photo model

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