Solved

Need help in Posting pasted image to PHP via Javascript

Posted on 2016-09-10
6
163 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 57

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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 
LVL 57

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 57

Expert Comment

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

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

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

Suggested Solutions

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

739 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