How to replace black background with white when resizing/converting PNG images with transparent backgrounds to JPEG.

♀尐吖头ヾ 提交于 2019-11-28 23:14:42
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]
user3125362

I found this other similar question here on this site. I hope it is helpful.

adding background color to transparent images using gd and php

Ok, this function is from php. As I've never worked with images on php, so I didn't know it.

So, images a composed of three colors: RGB (red, green, blue). In case of PNG, it's also composed of another filter, called alpha, which is the transparency

SO, just for PNG, you should switch imagecolorallocate to imagecolorallocatealpha($file,$i,$i,$i,$i);

This should make your images transparent. Does this solve your problem or do you really need them in white background?

Edit: I also noted that you are using imagejpg function in all cases. Switch them to the corresponding function, i.e., imagepng, imagebmp, imagegif

Try like this (not tested):

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

(predraw a white background on $file image)

Also, the for($i=0; $i<256; $i++) { imagecolorallocate($file, $i, $i, $i); } part looks strange.

After Image true colour add the lines:

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

This will help in mailtaining alpha for all formats. Ping if u dont get answer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!