Подтвердить что ты не робот

Как заменить черный фон белым при изменении размера/конвертации изображений PNG с прозрачным фоном в JPEG.

Я использую script, который позволяет пользователям загружать изображения. script изменяет размер и преобразует изображения в JPEG.

Проблема заключается в том, когда загружается PNG с прозрачностью, получающееся изображение JPEG является черным, где есть прозрачность.

Как я могу изменить ниже script, чтобы заменить черный на белый? Он уже делает это для GIF, но не для PNG.

 // RESIZE IMAGE AND PUT IN USER DIRECTORY
  switch($this->file_ext)
{
    case "gif":
      $file = imagecreatetruecolor($width, $height);
      $new = imagecreatefromgif($this->file_tempname);
      $kek=imagecolorallocate($file, 255, 255, 255);
      imagefill($file,0,0,$kek);
      imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
      imagejpeg($file, $photo_dest, 100);
      ImageDestroy($new);
      ImageDestroy($file);
      break;

    case "bmp":
      $file = imagecreatetruecolor($width, $height);
      $new = $this->imagecreatefrombmp($this->file_tempname);
      for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
      imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height); 
      imagejpeg($file, $photo_dest, 100);
      ImageDestroy($new);
      ImageDestroy($file);
      break;

    case "jpeg":
    case "jpg":
      $file = imagecreatetruecolor($width, $height);
      $new = imagecreatefromjpeg($this->file_tempname);
      for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
      imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
      imagejpeg($file, $photo_dest, 100);
      ImageDestroy($new);
      ImageDestroy($file);
      break;

    case "png":
      $file = imagecreatetruecolor($width, $height);
      $new = imagecreatefrompng($this->file_tempname);
      for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
      imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height); 
      imagejpeg($file, $photo_dest, 100);
      ImageDestroy($new);
      ImageDestroy($file);
      break;
  } 

  chmod($photo_dest, 0777);

  return true;
}

Я попробовал отредактировать часть case "png":, чтобы соответствовать тому, что в коде case "gif":, но полученный JPEG полностью белый.

UPDATE:

Я сам его исправил.

Спасибо, всем, за вклад!

Я заменил:

case "png":
      $file = imagecreatetruecolor($width, $height);
      $new = imagecreatefrompng($this->file_tempname);
      for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); }
      imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height); 
      imagejpeg($file, $photo_dest, 100);
      ImageDestroy($new);
      ImageDestroy($file);
      break;

с:

case "png":
      $file = imagecreatetruecolor($width, $height);
      $new = imagecreatefrompng($this->file_tempname);
      $kek=imagecolorallocate($file, 255, 255, 255);
      imagefill($file,0,0,$kek);
      imagecopyresampled($file, $new, 0, 0, 0, 0, $width, $height, $this->file_width, $this->file_height);
      imagejpeg($file, $photo_dest, 100);
      ImageDestroy($new);
      ImageDestroy($file);
      break;
4b9b3361

Ответ 2

Хорошо, эта функция от php. Поскольку я никогда не работал с изображениями на php, поэтому я не знал этого.

Итак, изображения a состоят из трех цветов: RGB (красный, зеленый, синий). В случае PNG он также состоит из другого фильтра, называемого альфа, который является прозрачностью

SO, только для PNG, вы должны переключить imagecolorallocate на imagecolorallocatealpha($file,$i,$i,$i,$i);

Это должно сделать ваши изображения прозрачными. Это решает вашу проблему или вам действительно нужны на белом фоне?

Edit: Я также отметил, что вы используете функцию imagejpg во всех случаях. Переключите их в соответствующую функцию, то есть imagepng, imagebmp, imagegif

Ответ 3

Попробуйте это (не проверено):

case "png":
  $file = imagecreatetruecolor($width, $height);
  $new = imagecreatefrompng($this->file_tempname);
  imagefilledrectangle ($file, 0, 0, $width, $height, imagecolorallocate($file, 0,0,0))

(предварите белый фон на $file image)

Кроме того, часть for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); } выглядит странно.

Ответ 4

switch($image_extension){
  case 'gif':
  case 'GIF':
    $image_orig_resource = imagecreatefromgif($image_orig_path);
    break;
  case 'png':
  case 'PNG':
    $image_orig_resource = imagecreatefrompng($image_orig_path);
    break;
  case 'jpg':
  case 'jpeg':
  case 'JPG':
  case 'JPEG':
    $image_orig_resource = imagecreatefromjpeg($image_orig_path);
    break;
  default:
    throw new Exception('Extension not supported');
}

$image_resource = imagecreatetruecolor($width, $height);
imagefill($image_resource, 0, 0, imagecolorallocate($image_resource, 255, 255, 255));  // white background;

imagecopyresampled($image_resource, $image_orig_resource, 0, 0, 0, 0, $width, $height, $image_orig_width, $image_orig_height);

imagejpeg($image_resource, $image_path, 100); // quality: [0-100]

Ответ 5

После изображения true color добавьте строки:

    $file = imagecreatetruecolor($width, $height);
    $background = imagecolorallocate($file, 0, 0, 0);
    imagecolortransparent($file, $background);
    imagealphablending($file, false);
    imagesavealpha($file, true);

Это поможет почтить альфа для всех форматов. Пинг, если вы не получите ответ.