Find JPEG resolution with PHP

后端 未结 5 897
隐瞒了意图╮
隐瞒了意图╮ 2020-12-28 11:09

Calling all PHP gurus!

I understand that you can use getimagesize() to get the actual pixel height and width of an image in PHP. However, if you open an image in pho

5条回答
  •  悲哀的现实
    2020-12-28 12:03

    There are two places that a resolution (i.e. resolution of the JPEG when printed, also referred to in shorthand as DPI or dots per inch) can potentially be stored.

    The first is in the JPEG's JFIF header, which is often (but NOT always) right at the start of the JPEG.

    The other is in the EXIF data.

    Note that resolution data is usually NOT present, as it only has meaning if associated with a physical output size. E.g. if a digital camera writes the value, it is usually meaningless . However, when the JPEG is being output to a printer (e.g.) then the value will have meaning.

    Here is some code to get it from the JFIF header, provided one is present, and is inside an APP0 chunk which is the second chunk in the file. (The first chunk is always the SOI marker.):

    function read_JFIF_dpi($filename)
    {
        $dpi = 0;
        $fp = @fopen($filename, r);
        if ($fp) {
            if (fseek($fp, 6) == 0) { // JFIF often (but not always) starts at offset 6.
                if (($bytes = fread($fp, 16)) !== false) { // JFIF header is 16 bytes.
                    if (substr($bytes, 0, 4) == "JFIF") { // Make sure it is JFIF header.
                        $JFIF_density_unit = ord($bytes[7]);
                        $JFIF_X_density = ord($bytes[8])*256 + ord($bytes[9]); // Read big-endian unsigned short int.
                        $JFIF_Y_density = ord($bytes[10])*256 + ord($bytes[11]); // Read big-endian unsigned short int.
                        if ($JFIF_X_density == $JFIF_Y_density) { // Assuming we're only interested in JPEGs with square pixels.
                            if ($JFIF_density_unit == 1) $dpi = $JFIF_X_density; // Inches.
                            else if ($JFIF_density_unit == 2) $dpi = $JFIF_X_density * 2.54; // Centimeters.
                        }
                    }
                }
            }
            fclose($fp);
        }
        return ($dpi);
    }
    

提交回复
热议问题