Evil Penguin
Evil Penguin

Reputation: 114

PHP imagecreatefromjpeg, imagecreatefrompng error handling

I want to omit parsing error message string of mentioned functions to get what exactly error means. Below is explanation why.

I have created following function for checking if image is valid JPEG or PNG and to check its integrity:

function validateImageByCreatingImageResource($filePath)
{
    $validationResult = true;
    $exif = exif_imagetype($filePath);
    if ($exif === false) {
        $validationResult = false;
    }
    if ($exif) {
        $imageResource = false;
        switch ($exif) {
            case IMAGETYPE_JPEG:
            case IMAGETYPE_JPEG2000:
                $imageResource = @imagecreatefromjpeg($filePath);
                break;
            case IMAGETYPE_PNG:
                $imageResource = @imagecreatefrompng($filePath);
                break;
        }
        if ($imageResource !== false) {
            imagedestroy($imageResource);
        }
    }
    $error = error_get_last();
    if (is_array($error)) {
        error_clear_last();
        $validationResult =  false;
    }
    return $validationResult;
}

Now, i can detect errors, but problem is with their handling. For example, here are 2 errors with type E_NOTICE:

  1. Reason: invalid end of file (wrong EOI mark)

    imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file

  2. Reason: additional data after EOI mark (inserted there by the device with which the picture was made)

    imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Invalid SOS parameters for sequential JPEG

My question: I surely can parse error message string, but is there a better way to handle this errors separately?

Also, i did not find any other solution (by using php tools) on how to validate image integrity.

===================================EDIT====================================

To clarify more: i need to determine what is exactly wrong with image, because i need to handle case where image is partially uploaded to server and allow images that are valid, but have additional information at the end of file after End Of Image mark.

array getimagesize ( string $filename [, array &$imageinfo ] )

provides array with this information:

[
    0 => integer width
    1 => integer height
    2 => integer type
    3 => string 'width="<width>" height="<height>"'
    bits => from what i understand it is color bits
    channels => integer number of channels
    mime => mime type eg. 'image/jpeg'
]

It gives warnings only when image metadata is invalid. No information about correct SOS markers like E_WARNING from imagecreatefromjpeg()

Upvotes: 0

Views: 2666

Answers (1)

wroniasty
wroniasty

Reputation: 8052

How about this:

array getimagesize ( string $filename [, array &$imageinfo ] )

Returns an array with image information, or FALSE if the image is invalid.

http://php.net/manual/en/function.getimagesize.php

Upvotes: 1

Related Questions