Add background colour to PNG file in PHP

This is sample code that I had posted on the PHP documentation comment that seem to have been deleted. Someone called “matt at mattostock dot com” posted code where this came from originally, but it didn’t work. This is designed to be called after the imagepng($im, $write_file) call.

<?php
 $bgColor = array (255,255,255); // white
 $pngData = bin2hex(file_get_contents($write_file));
 $pngDataOut = substr($pngData, 0, 16);
 // TODO: verify this is the correct PNG header
 $pngData = substr($pngData, 16);
 $fs = 100; // prevent infinite loop
 while (--$fs>0 && $pngData!='')
 {
 $chunkName = substr($pngData, 8, 8);
 $chunkSize = substr($pngData, 0, 8);
 $chunkSizeNumber = base_convert($chunkSize, 16, 10) * 2;
 if ($chunkName=='49444154')
 {
 // here we have found the first IDAT so we insert our bKGD
 $bkgdChunk = '624b4744';
 foreach ($bgColor as $bit)
 {
 $bkgdChunk .= sprintf('%04x',$bit);
 }
 $bkgdChunk .= sprintf('%08x', crc32(pack('H*', $bkgdChunk))) . '';
 $pngDataOut .= '00000006' . $bkgdChunk;
 break;
 }
 // TODO: omit any other bKGD chunks
 $pngDataOut .= substr($pngData, 0, 8+16+$chunkSizeNumber);
 $pngData = substr($pngData, 8+16+$chunkSizeNumber);
 }
 $pngDataOut .= substr($pngData, 0);
 file_put_contents($write_file, pack('H*', $pngDataOut));

Comments are closed.