javascript - 如何将画布图像保存为数据库并生成 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');
}
}
解决方案
您有 2 个选项:
- 如果您使用
toDataURL
,那么您将把图像作为 Base64 编码数据上传,即一个简单的表单字段 - 如果您使用
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) { ...... }
});
}
推荐阅读
- arrays - Matlab大数组减去
- arrays - 由于通配符和其他特殊字符,使用数组存储循环执行命令的 BASH 脚本失败
- r - 使用 Excel 文件在 ggplot2 中创建森林图
- xml - 替换 MPEG DASH 视频的片段
- wordpress - 在 x 个帖子后插入 adsense 广告
- c# - 使用 Ably.io 创建连接时出现未知错误
- java - 从 Java 调用(工作的)REST WebService 冻结而没有响应
- jquery - 显示动态行中行之间的项目总和
- web3 - 无法通过 npm 调用 web3 api(getTransactionReceipt)
- phantomjs - 使用 phantomjs 进行 Odoo 测试 - page.evaluate 评估结果:false