上传从画布创建的图像

时间:2017-03-12 21:12:52

标签: javascript php canvas

我试图从canvas元素创建一个img对象并将图像上传到服务器:

  var img = new Image();
  img.src = c2.toDataURL("image/jpeg", 0.95);  // c2 is the canvas element
  var formData = new FormData();
  formData.append('img', img);
  $.ajax({
      url: 'pro01.php',
      cache:false,
      contentType: false,
      processData: false,
      type: 'post',
      data: formData,
      success: function(data) {
        console.log(data);
      }
  });

pro01.php

$img = $_FILES['img'];
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
move_uploaded_file($_FILES["img"]["tmp_name"], $target_file);

控制台: <b>Notice</b>: Undefined index: img in...

任何帮助?

1 个答案:

答案 0 :(得分:1)

而不是将其设为图像,只需将画布转换为base64

var canvas = document.getElementById('myCanvas');
var dataURL = canvas.toDataURL();

现在发送:

$.ajax({
  type: "POST",
  url: "pro01.php",
  data: { 
     imgBase64: dataURL
  }

在php( pro01.php )中接收它:

从帖子请求中获取,删除开始并在发布的值上调用base64_decode()

$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$fileName = 'photo.png';
file_put_contents($fileName, $fileData);