Solved

Need help in Posting pasted image to PHP via Javascript

Posted on 2016-09-10
6
195 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 58

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 110

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
Use Filtering Commands to Process Files in Linux

Learn how to manipulate data with the help of various filtering commands such as `cat`, `fmt`, `pr`, and others in Linux.

 
LVL 58

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 58

Expert Comment

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

Featured Post

Don't Cry: How Liquid Web is Ensuring Security

WannaCry is just the start. Read how Liquid Web is protecting itself and its customers against new threats.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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.

635 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