claviska / SimpleImage

A PHP class that makes working with images and GD as simple as possible.
MIT License
1.38k stars 382 forks source link

PNG to JPG is possible to change transparent background color? #298

Closed BodyEND closed 2 years ago

BodyEND commented 2 years ago

Hi, i want to ask if is possible to change transparent background to white color, because now if i resize PNG to JPG, all transparent color is converted to black color. Thank you.

BodyEND commented 2 years ago

So to achieve that background transparency color change: i changed: public function fromFile($file)

to

case 'image/png':
      $this->image = imagecreatefrompng($file);

      $width = imagesx($this->image);
      $height = imagesy($this->image);
      $imageNew = imagecreatetruecolor($width, $height);
      imagefill($imageNew, 0, 0, imagecolorallocate($imageNew, 255, 255, 255));  // white background;
      imagecopyresampled($imageNew, $this->image, 0, 0, 0, 0, $width, $height, $width, $height);
      imagedestroy($this->image); 
      $this->image=$imageNew;

break;

it's not perfect solution, but is working. Can i achieve this with some build in function? Thank you for answer

claviska commented 2 years ago

This is untested, but something like this should do it.

$originalImage->fromFile($filename);

$newImage
  ->fromNew($originalImage->getWidth(), $originalImage->getHeight, $color)
  ->overlay($originalImage)
  ->toFile($newFilename, 'image/jpeg');

More info can be found in the readme: https://github.com/claviska/SimpleImage#api