save html5 canvas output to my rails app

后端 未结 2 616
一个人的身影
一个人的身影 2021-01-01 06:51

I am trying to save the content of a html5 canvas to my Rails app. I found the

var url = canvas.toDataURL(\'image/png\');

but I cant figur

相关标签:
2条回答
  • 2021-01-01 07:17

    The accepted answer didn't cover the carrierwave portion so here it is as I have it working in my app:

    In my profile_images_contoller.rb I added the following functions:

    # Convert base64 to binary
    def split_base64(uri_str)
      if uri_str.match(%r{^data:(.*?);(.*?),(.*)$})
        uri = Hash.new
        uri[:type] = $1 # "image/gif"
        uri[:encoder] = $2 # "base64"
        uri[:data] = $3 # data string
        uri[:extension] = $1.split('/')[1] # "gif"
        return uri
      else
        return nil
      end
    end
    
    # Convert data uri to uploaded file. Expects object hash, eg: params[:profile_image]
    def convert_data_uri_to_upload(obj_hash)
      if obj_hash[:remote_image_url].try(:match, %r{^data:(.*?);(.*?),(.*)$})
        image_data = split_base64(obj_hash[:remote_image_url])
        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)
    
        obj_hash[:image] = uploaded_file
        obj_hash.delete(:remote_image_url)
      end
    
      return obj_hash    
    end
    

    Then in my "create" action I passed convert_data_uri_to_upload(params[:profile_image]) to ProfileImage.new()

    def create
      @profile_image           = ProfileImage.new(convert_data_uri_to_upload(params[:profile_image]))
      @profile_image.imageable = @imageable
    
      respond_to do |format|
        if @profile_image.save
          format.html { redirect_to @entity_redirect_edit_path, notice: 'Profile image was successfully created.' }
          format.json { render json: @profile_image, status: :created, location: @profile_image }
        else
          format.html { render action: "new" }
          format.json { render json: @profile_image.errors, status: :unprocessable_entity }
        end
      end
    end
    

    Source: http://www.davehulihan.com/uploading-data-uris-in-carrierwave/

    0 讨论(0)
  • 2021-01-01 07:22

    simply place the content of url in an hidden field.

    <input type="hidden" name="canvascontent" id="canvascontent" />
    

    in javascript (with jquery):

    var url = canvas.toDataURL('image/png');
    $("#canvascontent").val(url);
    
    0 讨论(0)
提交回复
热议问题