首页 > 解决方案 > 如何将画布图像保存为数据库并生成 url

问题描述

如何将画布图像保存为数据库并生成 url

我正在使用下面的脚本在生成图像后生成图像,我想在提交表单时将画布保存或上传到数据库

我应该使用 HTML 表单和上传脚本

function takeSnapshot(){
  // Here we're using a trick that involves a hidden canvas element.  

  var hidden_canvas = document.querySelector('canvas'),
      context = hidden_canvas.getContext('2d');

  var width = video.videoWidth,
      height = video.videoHeight;

  if (width && height) {

    // Setup a canvas with the same dimensions as the video.
    hidden_canvas.width = width;
    hidden_canvas.height = height;

    // Make a copy of the current frame in the video on the canvas.
    context.drawImage(video, 0, 0, width, height);

    // Turn the canvas image into a dataURL that can be used as a src for our photo.
    return hidden_canvas.toDataURL('image/png');

  }
}
 <canvas id="canvas" width="300" height="300"></canvas> 

function takeSnapshot(){
  // Here we're using a trick that involves a hidden canvas element.  

  var hidden_canvas = document.querySelector('canvas'),
      context = hidden_canvas.getContext('2d');

  var width = video.videoWidth,
      height = video.videoHeight;

  if (width && height) {

    // Setup a canvas with the same dimensions as the video.
    hidden_canvas.width = width;
    hidden_canvas.height = height;

    // Make a copy of the current frame in the video on the canvas.
    context.drawImage(video, 0, 0, width, height);

    // Turn the canvas image into a dataURL that can be used as a src for our photo.
    return hidden_canvas.toDataURL('image/png');

  }
}

标签: javascripthtml

解决方案


您有 2 个选项:

  1. 如果您使用toDataURL,那么您将把图像作为 Base64 编码数据上传,即一个简单的表单字段
  2. 如果您使用toBlob,那么您可以将图像作为二进制文件上传,以便您可以使用$_FILES(如果您的后端是 PHP)

在这两种情况下,您都将在 AJAX 请求中使用 FormData:

var data = new FormData;
hidden_canvas.toBlob(sendImage, 'image/png');

function sendImage(blob_data)
{
  data.append('file_field', blob_data, 'snapshot_1.png');
  $.ajax( {
    url        : '/upload.php',
    type       : 'POST',
    contentType: false,
    cache      : false,
    processData: false,
    dataType   : 'json',
    data       : formData,
    success    : function (data) { ...... },
    error      : function (req, status, err) { ...... }
  });
}

推荐阅读