What are some best practices for handling file sizes in PHP when manipulating images?
When manipulating images in PHP, it is important to consider file sizes to prevent bloating and slow loading times. One best practice is to compress images before saving them to reduce file size without compromising quality. This can be achieved using functions like imagejpeg(), imagepng(), or imagegif() with the appropriate compression settings.
// Example of compressing and saving an image in PHP
$sourceImage = imagecreatefromjpeg('input.jpg');
$compressedImage = 'output.jpg';
// Compress the image with quality set to 80 (adjust as needed)
imagejpeg($sourceImage, $compressedImage, 80);
// Free up memory
imagedestroy($sourceImage);