The cart is empty

Converting images between different formats is a common task in Web development. If you need to convert images from PNG to JPG format using PHP, you can easily accomplish this task using a suitable library. Here's a PHP script that allows you to convert an image from PNG to JPG:

<?php
// Path to the input PNG file
$pngFile = 'input_image.png';

// Load the PNG image
$pngImage = imagecreatefrompng($pngFile);

// Create a new image in JPG format with white background
$jpgImage = imagecreatetruecolor(imagesx($pngImage), imagesy($pngImage));
$whiteColor = imagecolorallocate($jpgImage, 255, 255, 255);
imagefill($jpgImage, 0, 0, $whiteColor);

// Copy content from PNG to JPG
imagecopy($jpgImage, $pngImage, 0, 0, 0, 0, imagesx($pngImage), imagesy($pngImage));

// Save the new image as JPG
$jpgFile = 'output_image.jpg';
imagejpeg($jpgImage, $jpgFile);

// Free memory
imagedestroy($pngImage);
imagedestroy($jpgImage);

echo "The image has been successfully converted from PNG to JPG.";
?>

How does this script work?

  • You specify the path to the input PNG file.
  • The script loads the PNG image using the imagecreatefrompng() function.
  • A new image is created in JPG format with a white background using the imagecreatetruecolor() and imagecolorallocate() functions.
  • Content from the PNG image is copied to the new JPG image using the imagecopy() function.
  • The new image is saved to a file in JPG format using the imagejpeg() function.
  • Finally, memory is freed using the imagedestroy() functions.

This way, you can easily create a PHP script to convert an image from PNG to JPG format. The converted image will have a smaller size and will be more suitable for web pages and applications.