title: PHP/GD: How to handle jpg transparency?
body: <p>JPG doesn't support transparency.</p>
  
  <p>Yet you can export an image with transparent areas from for example GIMP. In that case the transparent areas will show either black or white in your browser, Windows explorer or other software.</p>
  
  <p>I regularly receive such files that I need to process and provide in several smaller formats. I do that with some PHP script using the GD library. The problem is that it is unpredictable whether those areas will turn out black or white in the processed versions. Even white backgrounds can turn into black.</p>
  
  <p>So my question is whether it is in some way possible to detect this "transparent" area in GD and assign it a specific color.</p>
  
  <p>See for example those two images:
  <a href="http://www.bilbil.com/9156-thickbox_default/bus.jpg" rel="nofollow noreferrer">http://www.bilbil.com/9156-thickbox_default/bus.jpg</a>
  <a href="http://bilbil.com/img/p/9/1/5/6/9156.jpg" rel="nofollow noreferrer">http://bilbil.com/img/p/9/1/5/6/9156.jpg</a></p>
  
  <p>At the moment I use this code:</p>
  
  <pre><code>$srcfile = "9158.jpg";
  $dir ="/test/";
  list($width, $height, $imgtype, $attr) = @getimagesize( $dir.$srcfile );
  $src = imagecreatefromjpeg($dir.$srcfile);
  $newheight=$newwidth = 800;
  $img = imagecreatetruecolor ( $newwidth , $newheight );
  $white = imagecolorallocate($img, 255, 255, 255);
  imagefill($img, 0, 0, $white);
  imagecopyresampled($img, $src, ($newwidth-$width)/2, ($newheight-$height)/2, 0, 0, $width, $height, $width, $height);
  if(!imagejpeg($img, $dir.'test.jpg', 97))
    echo("Error creating testimage");
  </code></pre>