Zulhilmi Zainudin
Zulhilmi Zainudin

Reputation: 9355

How to save canvas as PNG image using PHP?

I'm passing user's score to make-image.php file using GET. I want the score passed on top of myCanvas background image. How to save this 2 items (background image) and the canvas (score) as 1 PNG image in a folder using PHP?

I'm using Canvas2Image scripts but I don't know how to do it.

Please help. I'm stucked.

This the make-image.php file:

<?php $score = $_GET['score']; ?>
<html>
    <head>
    <script src="base64.js"></script>
    <script src="canvas2image.js"></script>
    <style type="text/css">

    body { margin: 0; }

    </style>
    </head>
    <body>
        <canvas id="myCanvas" width="300" height="300" style="border:1px solid #d3d3d3;background:url(http://i.imgur.com/PWSOy.jpg);"></canvas>
        <script type="text/javascript">

            var score = <?php echo $score; ?>;
            var canvas = document.getElementById('myCanvas');
            var context = canvas.getContext('2d');
            var x = canvas.width / 2;
            var y = canvas.height / 2;

            context.font = '30pt Calibri';
            context.textAlign = 'center';
            context.fillStyle = 'black';
            context.fillText(score, x, y);

      </script>
    </body>
</html>

Upvotes: 0

Views: 1748

Answers (1)

Daan
Daan

Reputation: 12246

Recently I programmed something for that no need for external libraries or something it's just a few lines of code

The $_POST['signature'] below would contain your base64 encoded image

define("UPLOAD_DIR", "images/signatures/");
$signature = $_POST['signature'];
$signature = str_replace('data:image/png;base64,', '', $signature);
$signature = str_replace(' ', '+', $signature);
$data = base64_decode($signature);
$file = UPLOAD_DIR . md5(microtime().date('Y-m-d')).'.png';
$success = file_put_contents($file, $data);

Upvotes: 2

Related Questions