Solved

Need help in Posting pasted image to PHP via Javascript

Posted on 2016-09-10
6
67 Views
1 Endorsement
Last Modified: 2016-09-12
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

1
Comment
Question by:golgo
  • 3
  • 2
6 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41793188
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
2
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41793279
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
0
 

Author Comment

by:golgo
ID: 41793335
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!
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41793433
I don't understand why you need two pages?

Just add the other inputs to the same form.
	<form method="POST" action="t1569.php" onsubmit="canvastoimage()">
		<input type="hidden" id="canvasimg" name="canvasimg" />
     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 class="btn btn-default" type="submit" />
	</form>	

Open in new window

I have updated the sample to include the other fields - the php script dumps the variables as well as showing the image.
0
 

Author Closing Comment

by:golgo
ID: 41793935
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
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41793956
You are most welcome.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
This Micro Tutorial will demonstrate using MozBar to view an article that was deleted from the Search Engine Watch site after being debunked by Google.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now