0

I'm trying to get image width and height from a jpg file extracted from PDF file using code:

if (file_exists($firstPagePath)) {
    if (is_readable($firstPagePath)) {
        list($width, $height) = getimagesize($firstPagePath);
    }
}

I have confirmed that it is correct image by running command line identify:

JPEG 1190x1684 1190x1684+0+0 8-bit sRGB 192302B 0.000u 0:00.000

File exists and it is readable but still it throws failed to open stream: No such file or directory error. I have already checked THIS but it didn't helped. I'm looking for any idea...

miken32
  • 42,008
  • 16
  • 111
  • 154
  • Can you confirm that the file is local, and that you aren’t using any stream wrappers? – Chris Haas Nov 26 '21 at 15:45
  • We can confirm that the file is local on the server where PHP process has full access rights. – Krystian Nov 26 '21 at 16:10
  • 1
    Please [edit] your question to include the full source code you have and the full complete error message you get from the execution of your PHP script. Also add a `var_dump(firstPagePath);` before the line you call `getimagesize()` (but still inside the `if()` block). – Progman Nov 26 '21 at 19:47

1 Answers1

0

Caution from getimagesize().

This function expects filename to be a valid image file. If a non-image file is supplied, it may be incorrectly detected as an image and the function will return successfully, but the array may contain nonsensical values.

Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead.

In case that the file is not an image it will be false anyway.

Use finfo() class to check the file must be image.

$finfo = new finfo();

if (is_file($firstPagePath) && stripos($finfo->file($firstPagePath, FILEINFO_MIME_TYPE), 'image/') !== false) {
    list($width, $height) = getimagesize($firstPagePath);
    var_dump($width);
    var_dump($height);
}

Note that file_exists() can check both folder and file if in the same name. Use is_file() to make sure that it is file and must be exists.

Use $finfo->file($firstPagePath, FILEINFO_MIME_TYPE) to retreive file's mime type and check with stripos() that it must be image/xxx for example image/jpeg.

You can use the $finfo->file() as shown above to echo out and see that what is your file's mime type.

vee
  • 4,506
  • 5
  • 44
  • 81
  • The file is definitely an image. – Krystian Nov 26 '21 at 16:11
  • Yes, sure. it is definitely an image but let's see your file's mime type. `$finfo = new finfo();` and then `echo $finfo->file($firstPagePath, FILEINFO_MIME_TYPE);` will be show the result from PHP that what is your file'e mime type. And try `var_dump(is_file(firstPagePath));` to debug that you file is really exists. – vee Nov 26 '21 at 16:15