Demystifying PHP’s Image Functions
The problem: I needed to find a way to upload jpg/gif/png formatted pictures to our server, crop, and resize them to be used as icons. There are plenty of resources available online for jpg and gif pictures. Png files, specifically with transparent backgrounds, proved a more challenging assignment.
The solution: Using several StackOverflow answers, PHP manual pages, and brute force, this is the most lightweight solution that worked for me. I will do my best to explain the why and how, though my understanding is murky at best. I hope this post can save someone even a fraction of the time it took me to arrive at the final solution.
I will only address the server-side implementation. On the client-side, I used JQuery’s Cropper library to manipulate the picture. So the
$src_y used in the
imagecopyresampled() function were received as $_POST variables by my endpoint. For simplification purposes, I’ve replaced those variables here to demonstrate how resizing works in the most straightforward way possible.
mime_content_type($filename) - Returns the MIME type of the media file. In my case, I only want to accept
imagecreatefrompng($filename) - Returns an ‘image resource identifier’ (or a special type of object that stores information about the image you’re creating) representing the image obtained from the
imagecreatetruecolor($width, $height) - Returns an image identifier representing a black image of the specified dimensions. Stackoverflow Answer
imagecolorallocatealpha($img, $red(0-255), $blue(0-255), $green(0-255), $alpha(0-127) - Allocates a color with transparency parameter ($alpha) for the image object created from imagecreatetruecolor(). 0 is opaque and 127 is transparent.
imagefill($image, $x, $y, $color) - Fill the given image with the given color.
imagecolortransparent($img, $color) - Gets or sets the transparent color from imagecolorallocatealpha() in the given image created by the imagecreatetruecolor().
imagecopyresampled($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) - Copies $src_img at coordinates ($src_x, $src_y) with dimensions $src_w, $src_h onto $dst_img retaining clarity despite shrinking the size. So in this case, we are resizing a 1500x1500 image to 100x100.
In English Please
Let’s translate that technical jargon to something we can wrap our heads around. I’m creating a black image resource identifier with the new size dimensions that I want and then setting its color attribute to be transparent. I then fill that image with the transparent color, physically changing the image from black to transparent. Finally, I am copying the uploaded image (
$filename) onto this new transparent image with the smaller dimensions. And that’s ALL it takes to resize an image icon in PHP!