GD warning : Premature end of JPEG file

Post Reply
tong
Site Admin
Posts: 2387
Joined: Fri 01 May 2009 8:55 pm

GD warning : Premature end of JPEG file

Post by tong »

Did you found that sometimes it hang the php when imagecreatefromjpeg() run on bad JPEG. I found that this is cause by the JPEG file U used don't have EOI (end of image), the FF D9 at the end of your JPEG

JPEG image should start with 0xFFD8 and end with 0xFFD9

Code: Select all

// this may help to fix the error
//check for jpeg file header and footer - also try to fix it

function check_jpeg($f, $fix=false )
{
    if ( false !== (@$fd = fopen($f, 'r+b' )) ){
        if ( fread($fd,2)==chr(255).chr(216) ){
            fseek ( $fd, -2, SEEK_END );
            if ( fread($fd,2)==chr(255).chr(217) ){
                fclose($fd);
                return true;
            }else{
                if ( $fix && fwrite($fd,chr(255).chr(217)) ){return true;}
                fclose($fd);
                return false;
            }
        }else{fclose($fd); return false;}
    }else{
        return false;
    }
}
tong
Site Admin
Posts: 2387
Joined: Fri 01 May 2009 8:55 pm

Re: GD warning : Premature end of JPEG file

Post by tong »

The solution is to tweak the PHP GD settings to ignore this warning
/etc/php.ini

Code: Select all

[gd]
; Tell the jpeg decode to ignore warnings and try to create
; a gd image. The warning will then be displayed as notices
; disabled by default
; http://www.php.net/manual/en/image.configuration.php#ini.image.jpeg-ignore-warning
gd.jpeg_ignore_warning = 1
tong
Site Admin
Posts: 2387
Joined: Fri 01 May 2009 8:55 pm

Re: GD warning : Premature end of JPEG file

Post by tong »

Perl Scalar

Code: Select all

# JPEG image should start with 0xFFD8 and end with 0xFFD9
# chr(255).chr(216) and chr(255).chr(217)
# Avoid the error : Premature end of JPEG file

if ( substr($content,  0, 2) ne chr(255).chr(216) or
     substr($content, -2, 2) ne chr(255).chr(217) 
   )
{
	die "Bad JPEG. $!";
}
tong
Site Admin
Posts: 2387
Joined: Fri 01 May 2009 8:55 pm

Re: GD warning : Premature end of JPEG file

Post by tong »

Perl FILEHANDLE

Code: Select all

open(JPG, "image.jpg");
seek(JPG, 0, SEEK_SET);
read(JPG, $top, 2);
seek(JPG, -2, SEEK_END);
read(JPG, $end, 2);
close(JPG);

if ( $top ne chr(255).chr(216) or
     $end ne chr(255).chr(217)
   )
{
     die "Bad JPEG. $!";
}
Post Reply