0

I want to Retrieve Image Resolution(DPI) of an image (JPEG,PNG,SVG,GIF) without using any PHP extension (like imageMagick). I searched everywhere, but I couldn't find a perfect solution. I tried below code (got from link)

function get_dpi($filename){
    $a = fopen($filename,'r');
    $string = fread($a,20);
    fclose($a);

    $data = bin2hex(substr($string,14,4));
    $x = substr($data,0,4);
    $y = substr($data,0,4);

    return array(hexdec($x),hexdec($y));
} 

But I am not getting the correct Horizontal and vertical DPI. For example, I used an image with 96dpi and 96dpi, but I got (100,100).And this function is only for JPEG file formats.

Community
  • 1
  • 1
Arun
  • 364
  • 2
  • 7
  • 19

1 Answers1

1

The DPI of an image is usually a matter of fiction. Rarely is an image created where the physical dimensions of the final rendering actually matter (as far as the image itself is concerned). That said, the DPI information is stored in the EXIF data of a JPEG so you can read it from there with the built-in PHP function:

<?php
    $filename = "/Users/quentin/Dropbox/Camera Uploads/2016-03-30 21.01.09.jpg";
    $exif = exif_read_data($filename);
?>

DPI is <?php echo $exif["XResolution"] ?> by <?php echo $exif["YResolution"] ?>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Hi Quentin, thanks for the answer. I checked the function, but I didn't get DPI information. This is what I got when I tried to print the exif data Array ( [FileName] => 1.jpg [FileDateTime] => 1350899542 [FileSize] => 150695 [FileType] => 2 [MimeType] => image/jpeg [SectionsFound] => IFD0, APP12 [COMPUTED] => Array ( [html] => width="700" height="420" [Height] => 420 [Width] => 700 [IsColor] => 1 [ByteOrderMotorola] => 0 ) [Company] => Ducky [Info] => ) – Arun Apr 01 '16 at 06:17
  • @Arun — Then, as far as I can tell, the file doesn't specify what size it wants to be printed at. As I said, the DPI is usually fictional anyway. Most people want to size the image to fit the document, or size it to fit the DPI/PPI of the printer/display rather than caring what size the image thinks it should be displayed at (and usually the person creating the image thinks the same and DPI is only added as a default by the graphics software). – Quentin Apr 01 '16 at 07:31
  • Thanks Quentin. Then I think, I have to use the imagemagicks. – Arun Apr 01 '16 at 09:57
  • If there isn't any DPI data then using a different tool to get it won't help. (I don't know if there is DPI data stored somewhere else or if ImageMagick will apply a default value if it can't find any). – Quentin Apr 01 '16 at 09:59