Search code examples
ruby-on-railscanvascamanjs

Save canvas to image on server upon form submit with Rails


i'm using Caman JS to manipulate an image in my edit view for the model Item.

$('#vintage').click(function() {
  Caman("#preview_image", function () {
    this.reset();
    this.crossProcess(100)
    this.render(function () {
      this.addClass('selected');
    });
  });
});

Caman JS provides me with an option to get the base64 value of the Canvas object

var dataURL = this.toBase64();

However i'm now kind of stuck what to do with this information. Ideally i'd like to overwrite the original image upon submitting my rails form.

Any suggestions would be great.


Solution

  • Ok, I found A solution. Here it is...

    create a hidden field with the base64 data as the value

    <input id="base64" type="hidden" value="" name="base64"/>
    var dataURL = this.toBase64();
    $('#base64').val(dataURL)
    

    I then processed this in my controller.

    unless params[:base64].empty?
      data =  params[:base64]
      image_data = Base64.decode64(data['data:image/png;base64,'.length .. -1])
      File.open("#{Rails.root}/public#{@item.image.url.to_s}", 'wb') do |f|
        f.write image_data
      end
      // Carierwave method to regenerate thumbnails
      @item.image.recreate_versions!
    end
    

    Might help someone, I'm still definitely open to suggestions for better or more efficient ways to do this.