Recent Posts

Showing posts with label image. Show all posts
Showing posts with label image. Show all posts

PHP: Save HTML5 canvas as an image in a server

Here is an example how to achieve what you need:

1) Draw something (taken from canvas tutorial)

<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    // begin custom shape
    context.beginPath();
    context.moveTo(170, 80);
    context.bezierCurveTo(130, 100, 130, 150, 230, 150);
    context.bezierCurveTo(250, 180, 320, 180, 340, 150);
    context.bezierCurveTo(420, 150, 420, 120, 390, 100);
    context.bezierCurveTo(430, 40, 370, 30, 340, 50);
    context.bezierCurveTo(320, 5, 250, 20, 250, 50);
    context.bezierCurveTo(200, 5, 150, 20, 170, 80);

    // complete custom shape
    context.closePath();
    context.lineWidth = 5;
    context.fillStyle = '#8ED6FF';
    context.fill();
    context.strokeStyle = 'blue';
    context.stroke();
</script>
2) Convert canvas image to URL format (base64)

var dataURL = canvas.toDataURL();
3) Send it to your server via Ajax

$.ajax({
  type: "POST",
  url: "script.php",
  data: { 
     imgBase64: dataURL
  }
}).done(function(o) {
  console.log('saved'); 
  // If you want the file to be visible in the browser 
  // - please modify the callback in javascript. All you
  // need is to return the url to the file, you just saved 
  // and than put the image in your browser.
});
3) Save base64 on your server as an image (here is how to do this in PHP:

My best guess is that you simply need to call base64_decode() on $_REQUEST['data'] before writing it to the file.

The same ideas is in every language. Server side in PHP can be found here):


How to: Save image from PHP URL

Let's say I have a page, http://example.com/image.php, holding a single "flower" image, nothing else. How can I save this image from the URL with a new name (using PHP)?

$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));
Else can use cURL

$ch = curl_init('http://example.com/image.php');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);