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
Solved

Need help in Posting pasted image to PHP via Javascript

Posted on 2016-09-10
6
122 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 55

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 109

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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 55

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 55

Expert Comment

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

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This video will take you through the Acquisition tab overview.  You will learn to navigate All Traffic and Organic Keywords. It will take you through the Social Overview, Site Content, and Real Time tabs. Click on Acquisition – Overview : Look at Al…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

839 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