How can I convert PNG images to JPG with compression in PHP while preserving quality and minimizing file size?

Patricia Arquette
Release: 2024-11-01 10:57:30
Original
897 people have browsed it

How can I convert PNG images to JPG with compression in PHP while preserving quality and minimizing file size?

Converting PNG to JPG with Compression in PHP

Question:

Seeking a method to convert PNG images to JPG in PHP while preserving quality and minimizing file size. How can this be achieved?

Answer:

PHP provides an image manipulation library that allows for easy conversion between image formats. Here's how to convert a PNG file to JPG with compression:

<code class="php">// Convert PNG image to JPG with transparency in white
$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);

// Set compression quality (0=worst, 100=best)
$quality = 50;

// Convert to JPG and save to new file
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);</code>
Copy after login

This code:

  1. Loads the PNG image.
  2. Creates a new image with a white background and transparent pixels.
  3. Copies the PNG image onto the white background.
  4. Specifies the compression quality for the JPG output.
  5. Converts to JPG and saves the result.

The above is the detailed content of How can I convert PNG images to JPG with compression in PHP while preserving quality and minimizing file size?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template