Uploaded images from inexperienced users often have issues, such as large file sizes.
The best solution in such cases is to handle the processing on the server side so the user feels more at ease. The simplest method for reducing image size is using the GD functions in PHP, which are installed on almost all active servers.
To reduce image size to a desired level, you only need a function and a few lines of code. The approach involves using the imagecopyresampled function to downscale the image pixels with acceptable quality.
Using the latest GD functions, we can handle images in various formats. In the function below, we first create a resource from the image based on its type. Then, using the specified maximum width and height, we generate a new image in JPG format.
This function takes two main parameters:
- The path to the image on the local or remote server.
- The path where the resized image should be saved — it can be the same as the original path.
function picture_lower_size($image_adress, $save_adress)
{
$max_width = 400; // max width of image (pixel)
$max_height = 400; // max height of image (pixel)
$file_type = mime_content_type($image_adress);
switch ($file_type) {
// check the file type for create resource
case 'image/jpeg':
$original_image = imagecreatefromjpeg($image_adress);
break;
case 'image/png':
$original_image = imagecreatefrompng($image_adress);
break;
case 'image/gif':
$original_image = imagecreatefromgif($image_adress);
break;
default:
die("wrong format");
break;
}
$dims = getimagesize($original_image);
$orginalWidth = $dims[0];
$orginalHeight = $dims[1];
if ($orginalWidth > $max_width) {
// set new width if it is large
$thumbHeight = ($orginalHeight * $max_width) / $orginalWidth;
$thumbWidth = $max_width;
}
if ($orginalHeight > $max_height) {
// set new height if it is large
$thumbWidth = ($orginalWidth * $max_height) / $orginalHeight;
$thumbHeight = $max_height;
}
$thumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagefilledrectangle($thumb, 0, 0, $thumbWidth, $thumbHeight, 0xFFFFFF);
imagecopyresampled($thumb, $original, 0, 0, 0, 0,
$thumbWidth, $thumbHeight, $orginalWidth, $orginalHeight);
// save the file as jpeg format
imagejpeg($thumb, $save_adress);
}
PHP


