What are common pitfalls when resizing images in PHP, and how can they be avoided?
Common pitfalls when resizing images in PHP include loss of image quality, distortion, and increased file size. To avoid these issues, it is important to use the appropriate image manipulation functions and settings, such as maintaining aspect ratio and choosing the right interpolation method.
// Example of resizing an image in PHP without losing quality or distorting the image
function resize_image($source_image_path, $new_image_path, $new_width, $new_height) {
list($source_width, $source_height) = getimagesize($source_image_path);
$source_image = imagecreatefromjpeg($source_image_path);
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $source_image, 0, 0, 0, 0, $new_width, $new_height, $source_width, $source_height);
imagejpeg($new_image, $new_image_path, 100);
imagedestroy($source_image);
imagedestroy($new_image);
}
// Usage
resize_image('source.jpg', 'resized.jpg', 200, 200);