Wednesday 10 August 2016

Image Data object to Image URI #rails #RUby On Rails #ImageData

# Convert data uri to uploaded file. Expects object hash, eg: params[:post]  def convert_data_uri_to_upload(data_uri)
    if !data_uri.blank?
      image_data = split_base64(data_uri)
      image_data_string = image_data[:data]
      image_data_binary = Base64.decode64(image_data_string)

      temp_img_file = Tempfile.new("data_uri-upload")
      temp_img_file.binmode
      temp_img_file << image_data_binary      temp_img_file.rewind

      img_params = {:filename => "data-uri-img.#{image_data[:extension]}", :type => image_data[:type], :tempfile => temp_img_file}
      uploaded_file = ActionDispatch::Http::UploadedFile.new(img_params)

      return uploaded_file    end
    return nil  end
 
 
 
 
OR 
 
 
require 'open-uri'def embed_remote_image(url, content_type)
  begin    # asset = open(url, "r:UTF-8") { |f| f.read }  rescue nil    asset = open(url, "r:UTF-8") { |f| f.read }
    base64 = Base64.encode64(asset.to_s).gsub(/\s+/, "")

    "data:#{content_type};base64,#{Rack::Utils.escape(base64)}"  rescue OpenURI::HTTPError => ex
  endend 

No comments:

Post a Comment