PNG: Druckgröße (DPI) abspeichern mit PHP

(Kommentare: 0)

Die PHP-Funktion imagepng() speichert keine Information zur Druckgröße in der resultierenden PNG-Datei (keine Angabe über Auflösung bzw. Druckgröße in DPI/dots per inch oder cm). Hier eine mögliche Lösung.

Die folgende Methode schreibt in die Ausgabe von PHP noch die entsprechende Information hinein.

<?php
    /** Writes png image file with given dpi resolution information 
      * (since php's imagepng() function does not do it).
      * Returns png as byte string. If filename is given, data is written to file and the method
      * returns the number of bytes written or FALSE if error.
      *
      * @param $image Image resource
      * @param $dpi dots per inch value for horizontal and vertical resolution 
      * @param $compression [0..9], 0 = lossless, 9 = maximum compression
      * @param $filename optional filename and if given the png is writte to file
      */
    function writePng($image, $dpi, $compression = 0, $filename = null) {
        $dpm = $dpi / 0.0254;

        // Let php write the png file...
        ob_start();
        imagepng($image, NULL, $compression, NULL);
        $content = ob_get_clean();

        // Split result to get a slot to insert our pHYs chunk...
        list($first, $second) = explode('IDAT', $content, 2);
        // This way we split the IDAT chunk between its length and type code, 
        // so we have to repair it...
        $idatlen = substr($first, strlen($first)-4, 4);
        $first = substr($first, 0, strlen($first)-4);
        $second = $idatlen . 'IDAT' . $second;
        
        // Now create pHYs chunk and insert...
        $data = pack('N', $dpm) . pack('N', $dpm) . chr(1);
        $len = pack('N', strlen($data));
        $type = 'pHYs';
        
        $phys = $len . $type . $data . pack('N', crc32($type . $data));

        $content = $first . $phys . $second;
        
        if ($filename) {
            // Save / store file...
            return file_put_contents($filename, $content);
        }
        return $content;
    }   
?>

 

Zurück

Kommentare

Einen Kommentar schreiben


Bitte geben Sie den Code ein, den Sie im Bild sehen.