Рубрики
Uncategorized

PHP обрабатывает изображение PNG белого цвета фона до прозрачного цвета пример кода

Автор оригинала: David Wong.

Посмотрите на следующий код, PHP обрабатывает изображение PNG, белый цвет фона изменен на прозрачный цвет

function pngMerge($o_pic,$out_pic){
 $begin_r = 255;
 $begin_g = 250;
 $begin_b = 250;
 List ($src_w, $src_h) = getimagesize ($o_pic); // Get the width of the original image information
 Src_im = image creation from mpng ($o_pic); // read PNG pictures
 print_r($src_im);
 Imagesavealpha ($src_im, true); // It's important not to lose the transparent color of the $src_im image.
 $src_white = image color allocation PHA ($src_im, 255, 255, 127); // Create a white transparent canvas
 for ($x = 0; $x < $src_w; $x++) {
  for ($y = 0; $y < $src_h; $y++) {
    $rgb = imagecolorat($src_im, $x, $y);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
    if($r==255 && $g==255 && $b == 255){
    Imagefill ($src_im, $x, $y, $src_white); // Fill in the color of a point
    Imagecolor transparent ($src_im, $src_white); // Replace the original color with transparent color
    }
    if (!($r <= $begin_r && $g <= $begin_g && $b <= $begin_b)) {
     Imagefill ($src_im, $x, $y, $src_white); // Replace with white
     Imagecolor transparent ($src_im, $src_white); // Replace the original color with transparent color
    }
  }
 }
 $target_im = imagecreatetruecolor ($src_w, $src_h);//new figure
 Imagealphablending ($target_im, false); // / It's important here to replace the color of the $target_im image directly with the color of the $target_im image, including transparent color.
 Imagesavealpha ($target_im, true); // This is important, meaning don't lose the transparent color of the $target_im image;
 $tag_white = image color allocation PHA ($target_im, 255, 255, 255, 127); /// Change the white that generates the new image to transparent color and save it as tag_white
 Imagefill ($target_im, 0, 0, $tag_white); // Fill blank white in the new target image
 Imagecolor transparent ($target_im, $tag_white); // Replace with transparent color
 Imagecopymerge ($target_im, $src_im, 0, 0, 0, $src_w, $src_h, 100); // merge the original and newly generated transparent images
 imagepng($target_im,$out_pic);
 return $out_pic;
}
$o_pic = '1.png';
$name = pngMerge($o_pic,'aaaa.png');
print_r($name);

Плюс: Замените фон изображения прозрачным фоном с помощью библиотеки PHP GD

Перед написанием функции с PHP, чтобы сделать фон картинки прозрачным, оставив текст (черный), я также нашел на Baidu, также пробовал чужой код. Именно так думает большинство программистов:

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

$o_pic = '1.jpg';
// Starting value of color order to be processed
$begin_r = 215;
$begin_g = 215;
$begin_b = 215;
List ($src_w, $src_h, $src_type) = getimagesize ($o_pic); // Get the original image information
$file_ext = get_ext ($o_pic); // Get the extension
$target_im = imagecreatetruecolor ($src_w, $src_h);//new figure
If ($file_ext=='jpg') // / Conversion JPG begins
{
  $src_im = ImageCreateFromJPEG($o_pic);
  imagecopymerge($target_im,$src_im,0,0,0,0,$src_w,$src_h,100);
  for($x = 0; $x < $src_w; $x++)
  {
    for($y = 0; $y < $src_h; $y++)
    {
      $rgb = imagecolorat($src_im, $x, $y);
      $r = ($rgb >> 16) & 0xFF;
      $g = ($rgb >> 8) & 0xFF;
      $b = $rgb & 0xFF;
      if($r > $begin_r && $g > $begin_g && $b > $begin_b ){  
        imagecolortransparent($target_im, imagecolorallocate($target_im,$r, $g, $b));        
      }
    }
  }
}

Но с этой идеей фон картины не был прозрачным, менялся много раз. Позже было обнаружено, что только последняя функция imagecolortransparent () была эффективной, и передняя часть была закрыта.

Измените образ мышления, сначала измените цвет, который вам не нужен, на белый, и, наконец, замените белый прозрачностью.

$begin_r = 98;
$begin_g = 98;
$begin_b = 98;
List ($src_w, $src_h) = getimagesize ($o_pic); // Get the original image information
$src_im = imagecreatefromjpeg($o_pic);
//imagecopymerge($target_im, $src_im, 0, 0, 0, 0, $src_w, $src_h, 100);
//imagecopyresampled($target_im, $src_im, 0, 0, 0, 0, $src_w, $src_h, $src_w, $src_h);
$i = 0;
$src_white = imagecolorallocate($src_im, 255, 255, 255);
for ($x = 0; $x < $src_w; $x++) {
  for ($y = 0; $y < $src_h; $y++) {
   $rgb = imagecolorat($src_im, $x, $y);
   $r = ($rgb >> 16) & 0xFF;
   $g = ($rgb >> 8) & 0xFF;
   $b = $rgb & 0xFF;
   if($r==255 && $g==255 && $b == 255){
     $i ++;
     continue;
   }
   if (!($r <= $begin_r && $g <= $begin_g && $b <= $begin_b)) {
     Imagefill ($src_im, $x, $y, $src_white); // Replace with white
   }
  }
}
$target_im = imagecreatetruecolor ($src_w, $src_h);//new figure
$tag_white = imagecolorallocate($target_im, 255, 255, 255);
imagefill($target_im, 0, 0, $tag_white);
imagecolortransparent($target_im, $tag_white);
imagecopymerge($target_im, $src_im, 0, 0, 0, 0, $src_w, $src_h, 100);

резюме

Выше приведен пример кода PHP, обрабатывающего изображение PNG, белый цвет фона которого изменен на прозрачный. Я надеюсь, что это будет полезно для вас. Если у вас есть какие-либо вопросы, пожалуйста, оставьте мне сообщение, и редактор ответит вам вовремя. Большое вам спасибо за вашу поддержку в развитии peer.