How to save an HTML5 Canvas as an image on a server?

后端 未结 8 2234
走了就别回头了
走了就别回头了 2020-11-21 23:50

I\'m working on a generative art project where I would like to allow users to save the resulting images from an algorithm. The general idea is:

  • Create an image
相关标签:
8条回答
  • 2020-11-22 00:38

    I think you should tranfer image in base64 to image with blob, because when you use base64 image, it take a lot of log lines or a lot of line will send to server. With blob, it only the file. You can use this code bellow:

    dataURLtoBlob = (dataURL) ->
      # Decode the dataURL
      binary = atob(dataURL.split(',')[1])
      # Create 8-bit unsigned array
      array = []
      i = 0
      while i < binary.length
        array.push binary.charCodeAt(i)
        i++
      # Return our Blob object
      new Blob([ new Uint8Array(array) ], type: 'image/png')
    

    And canvas code here:

    canvas = document.getElementById('canvas')
    file = dataURLtoBlob(canvas.toDataURL())
    

    After that you can use ajax with Form:

      fd = new FormData
      # Append our Canvas image file to the form data
      fd.append 'image', file
      $.ajax
        type: 'POST'
        url: '/url-to-save'
        data: fd
        processData: false
        contentType: false
    

    This code using CoffeeScript syntax.

    if you want to use javascript, please paste the code to http://js2.coffee

    0 讨论(0)
  • 2020-11-22 00:42

    Send canvas image to PHP:

    var photo = canvas.toDataURL('image/jpeg');                
    $.ajax({
      method: 'POST',
      url: 'photo_upload.php',
      data: {
        photo: photo
      }
    });
    

    Here's PHP script:
    photo_upload.php

    <?php
    
        $data = $_POST['photo'];
        list($type, $data) = explode(';', $data);
        list(, $data)      = explode(',', $data);
        $data = base64_decode($data);
    
        mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos");
    
        file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/".time().'.png', $data);
        die;
    ?>
    
    0 讨论(0)
提交回复
热议问题