Avatar of golgo
golgo
Flag for Japan asked on

Need help in Posting pasted image to PHP via Javascript

I'm a total Javascript-illiterate, but I need your help in modifying the following code so that it can

  1. allow users to paste their clipboard image (via Chrome), and
  2. upload the image along with other user input to my PHP script via POST.

I'd much appreciate it if you could help....



<!DOCTYPE html>
<html>
<head>

<title>Paste-able Canvas</title>
<script type="text/javascript">

function enablePasteForCanvas(canvas) {
  var pasteEvent = function(e) {
    (function() {
      var i;
      // Search image data in the clipboard 
      var items = e.clipboardData.items;
      var imageItem = null;
      for(i = 0; i < items.length; i++) {
        if(items[i].type.indexOf("image/") != -1) {
          imageItem = items[i];
          break;
        }
      }
      if(! imageItem) {
        console.log("clipboard does not contain an image.");
        return;
      }
      
      //convert:  clipboardData.items -> Blob -> Image 
      var blob = imageItem.getAsFile();
      var blobUrl = window.URL.createObjectURL(blob);
      var img = new Image();
      img.onload = function() {
        //Draw the image on canvas
        var context = canvas.getContext("2d");
        context.drawImage(img, 0, 0);
		
      };
      img.src = blobUrl;
    }());
    e.preventDefault();
  };
  
  canvas.addEventListener("focus", function(e){
    document.addEventListener("paste", pasteEvent, false);
  }, false);
  canvas.addEventListener("blur", function(e){
    document.removeEventListener("paste", pasteEvent, false);
  }, false);
}

window.addEventListener("load",function(e){
  enablePasteForCanvas(document.getElementById("my_canvas"));
}, false);


</script>

</head>
<body>

  <h2>Paste an image below</h2>(use Cntl + V)
  <br><br>Browswer:  Chrome only.<br>
  <table border=1 width=640><tr><td>
  
     <canvas id="my_canvas" width="640" height="280" tabindex="2"></canvas>

  </table>
  <br><br>
  

  <form type=POST action=drag.php>

     Text:  <input type=textbox name=text_1 width=10><br><br>
     Color: <input type=radio name=radio_1 value=blue> Blue  
	          <input type=radio name=radio_1 value=red> Red  <br><br><br>

   <input type=submit name=submit value=submit>

</form>
  
  
</body>
</html>

Open in new window

JavaScriptPHPAJAXGoogle Chrome OSjQuery

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
Julian Hansen

You need to do to things
1. Add a hidden input to your form to store the data in
2. Either in your paste event handler or onsubmit handler put the contents of the canvas into the control

The following sample adds an onsubmit handler to add the image on submit
HTML
	<h2>Paste an image below</h2>(use Cntl + V)
	<br><br>Browswer:  Chrome only.<br>

	<div style="margin: 0 auto">
	     <canvas id="my_canvas" width="640" height="280" tabindex="2"></canvas>
	</div>

	<form method="POST" action="reflect.php" onsubmit="canvastoimage()">
		<input type="hidden" id="canvasimg" name="canvasimg" />
		<input class="btn btn-default" type="submit" />
	</form>	

Open in new window

JavaScript
...
function canvastoimage()
{
	var canvas = document.getElementById('my_canvas');
	document.getElementById('canvasimg').value = canvas.toDataURL();
}

Open in new window

PHP
<?php
echo "POST\n";
echo "<pre>" . print_r($_POST, true) . "</pre>";
if (isset($_POST['canvasimg'])) {
  $img = $_POST['canvasimg'];
  $img = str_replace('data:image/png;base64,', '', $img);
  $img = str_replace(' ', '+', $img);
  $data = base64_decode($img);
  file_put_contents('images/canvasimg.png', $data);
  if (exif_imagetype('images/canvasimg.png') != IMAGETYPE_PNG) {
    unlink('images/canvasimg.png');
  }
  else {
    echo '<img src="images/canvasimg.png" />';
  }
}

Open in new window

Working sample here
Ray Paseur

This is a very cool idea, but I wonder about the efficacy of an application that doesn't work for the majority of browsers.  It might be worth triggering some kind of alternate event to prompt / redirect the client to save the clipboard if a non-Chrome browser encounters the application.  I don't know how to do that -- just a thought...
https://upload.wikimedia.org/wikipedia/commons/e/e9/Web-browser_usage_on_Wikimedia.png
golgo

ASKER
Dear Julian,

I'm blown away by your codes (including the php script) !!
Thank you so much!  

...but going hidden inputs would make it a two-step process (requiring two pages)...
I apologize for being greedy while I'm being helped so much, is there any way that we could send the image and the user texts (via <input> tags) at the same time...?

And Ray, thank you for the stats, too!  That's a good point, and thank you again, Julian, for adding the filter too!
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
golgo

ASKER
Sorry Julian,
I must have misunderstood what you meant.

Wow....
Thank you so much for your quick help.
You have no idea how thankful I am to you after having pulled out my hair over this for a week and almost gave up.
Thank you SO MUCH, Julian!

Elpmet
Julian Hansen

You are most welcome.