PHP add iTXt comment to a PNG image

前端 未结 1 1229
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 13:05

I have looked around for this everywhere. I know it can be done using some libraries in .net, but I really want my script to generate a \"marked\" image. The reason is that we a

相关标签:
1条回答
  • 2021-01-26 13:14

    A suggestion: If you have a fixed iTXt chunk that you want to add to an image, a quick and dirty procedure could be to simply insert it just before the IEND chunk (12 bytes) of the original image. This should work, because the iTXt can be placed before of after the image data. Of course, this does not check if the chunk as already there.

    Here's an example code, using the tEXt chunk (slightly simpler), it needs some polishing but it basically works:

    <?php   
    
        addTextToPngFile("x.png","x2.png","Watermark","Hi this is a TEXT test");
    
        function addTextToPngFile($pngSrc,$pngTarget,$key,$text) {
            $chunk = phpTextChunk($key,$text);
            $png = file_get_contents($pngSrc);
            $png2 = addPngChunk($chunk,$png);
            file_put_contents($pngTarget,$png2);
        }
    
        // creates a tEXt chunk with given key and text (iso8859-1)
        // ToDo: check that key length is less than 79 and that neither includes null bytes
        function phpTextChunk($key,$text) {
            $chunktype = "tEXt";
            $chunkdata = $key . "\0" . $text;
            $crc = pack("N", crc32($chunktype . $chunkdata));
            $len = pack("N",strlen($chunkdata));
            return $len .  $chunktype  . $chunkdata . $crc;
        }
    
        // inserts chunk before IEND chunk (last 12 bytes)
        function addPngChunk($chunk,$png) {
            $len = strlen($png);
            return substr($png,0,$len-12) . $chunk . substr($png,$len-12,12);
        }
    
    ?>
    
    0 讨论(0)
提交回复
热议问题