Alon
Alon

Reputation: 7758

How to create a PNG file in any scripting language for web use

let's just say I want to give my web user the ability to give a radius size (let's say 5px) and then send him/her back a png file with a circle in this radius.

so I guess my question has 2 sections:

  1. How can I create an "image request" (which language and technologies) to get a PNG file, where is the file created and how
  2. I guess there is an API how to draw it but I need to know where is a good place to start to start.

I need to know where to start because this is a field I haven't explored yet.

Upvotes: 3

Views: 2418

Answers (1)

Robin
Robin

Reputation: 8518

A very simple example with PHP:

<?php
// Create a blank image.
$image = imagecreatetruecolor(400, 300);
// Select the background color.
$bg = imagecolorallocate($image, 0, 0, 0);
// Fill the background with the color selected above.
imagefill($image, 0, 0, $bg);
// Choose a color for the ellipse.
$col_ellipse = imagecolorallocate($image, 255, 255, 255);
// Draw the ellipse.
imageellipse($image, 200, 150, $_GET['w'], $_GET['w'], $col_ellipse);
// Output the image.
header("Content-type: image/png");
imagepng($image);
?>

You have to call the script with the parameter w. e.g image.php?w=50 Mostly stolen from here.

And a little example with JavaScript and Canvas:

<!DOCTYPE html>
<html>
<body>
canvas:
<canvas id="myCanvas" width="100" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>

<script type="text/javascript">

    var c=document.getElementById("myCanvas");
    var cxt=c.getContext("2d");


    function getParameterByName(name){
          name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
          var regexS = "[\\?&]" + name + "=([^&#]*)";
          var regex = new RegExp(regexS);
          var results = regex.exec(window.location.href);
          if(results == null)
            return "";
          else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    cxt.fillStyle="#FF0000";
    cxt.beginPath();
    cxt.arc(50,50,getParameterByName("w"),0,Math.PI*2,true);
    cxt.closePath();
    cxt.fill();
    document.write('png:<img src="'+c.toDataURL("image/png")+'"/>');
</script>

</body>
</html>

You have still call the script with the parameter w. e.g image.html?w=50 This, this and @Phrogz helped me.

Upvotes: 4

Related Questions