How to create transparent image with PHP


Method 1: use imagecolorallocatealpha and imagesavealpha

<?php

$width = 200;
$height = 200;
// create the output image. 
$img=imagecreatetruecolor( $width, $height ); 

// Allocate a transparent color and fill the new image with it. 
// Without this the image will have a black background instead of being transparent. 
$transparent = imagecolorallocatealpha( $img, 0, 0, 0, 127 ); 
imagefill( $img, 0, 0, $transparent ); 

// Do something
$corners[0] = array('x' => 100, 'y' =>  10);
$corners[1] = array('x' =>   0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);

$red = imagecolorallocate($img, 255, 0, 0); 

for ($i = 0; $i < 100000; $i++) {
  imagesetpixel($img, round($x),round($y), $red);
  $a = rand(0, 2);
  $x = ($x + $corners[$a]['x']) / 2;
  $y = ($y + $corners[$a]['y']) / 2;
}
//end do something

// save the alpha 
imagesavealpha($img,true); 

// emit the image 
header('Content-type: image/png'); 
imagepng( $img ); 

// dispose 
imagedestroy($img); 
?>

Online demo:

Method 2: use imagecolortransparent

<?php
// Create a 200x200 image
$im = imagecreatetruecolor(200, 200);
$red = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);

// Make the background transparent
imagecolortransparent($im, $black);

// Draw a red border
imagerectangle($im,0,0, 200-2, 200-2, $red);

// Draw a String
imagestring($im, 5, 22, 90, 'TUTORIALSPOTS.COM', $red);

header('Content-type: image/png'); 
imagepng( $im ); 
 
// dispose 
imagedestroy($im);
?>

Online demo:

Leave a Reply