Page 279 - Open Soource Technologies 304.indd
P. 279
Unit 11: Graphics
Notes
$im = imagecreatefromjpeg($source);
Next step is to create an empty image canvas onto which we will copy the scaled image data.
We will use the calculated destination dimensions as arguments to the “imagecreatetruecolor()”
function.
$newim = imagecreatetruecolor($x,$y);
Probably the most complex part of this script is the “imagecopyresampled()” function. It takes
10 arguments in all. The first is the destination image object, then the source image object, then
the next four are x and y position values for the destination and source images respectively,
then the destination x and y dimensions respectively, then the source image x and y dimensions
respectively.
imagecopyresampled($newim, $im, 0, 0, 0, 0, $x, $y, $imsize[0], $imsize[1]);
Now that the image has been scaled and moved to our destination image object, we just need
to save it. We can save it to a JPG file regardless of the source file type using the “imagejpeg()”.
Parameters are destination image object, desired output file path, and then the quality variable
(integer from 0 to 100, 100 being the best quality).
imagejpeg($newim, $dest, $quality);
You now have a new JPG image created under the “$dest” filename. Here is a reiteration of all
the code show above:
$source = “source_image.jpg”;
$dest = “resized_image.jpg”;
$quality = 100;
$scale = 1/2;
$imsize = getimagesize($source);
$x = $scale * $imsize[0];
$y = $scale * $imsize[1];
$im = imagecreatefromjpeg($source);
$newim = imagecreatetruecolor($x,$y);
imagecopyresampled($newim, $im, 0, 0, 0, 0, $x, $y, $imsize[0], $imsize[1]);
imagejpeg($newim, $dest, $quality);
11.8 Colour Handling
Colour support improved markedly between GD 1.x and GD 2.x. In GD 1.x there was no notion
of the alpha channel, colour handling was rather simple, and the library supported only 8-bit
palette images (256 colors). When creating GD 1.x 8-bit palette images, you use the ImageCreate( )
function, and the first colour you allocate using the ImageColorAllocate( ) function becomes
the background colour.
LOVELY PROFESSIONAL UNIVERSITY 273