How to detect if the jpg jpeg image file is corrupted(incomplete)?

前端 未结 2 440
南方客
南方客 2020-12-19 06:38

I have to show some images from others\' image server on my website but some of the images from the image server can only partially show like below image

The image

2条回答
  •  不思量自难忘°
    2020-12-19 07:11

    I created a JPEG to test this using ImageMagick as follows:

    convert -size 1024x768 gradient: image.jpg
    

    and it was 14kB. Your image looks like it is incomplete, so I chopped off everything after 3kB like this:

    dd if=image.jpg bs=3000 count=1 > corrupt.jpg
    

    Now, if I run ImageMagick's identify command and discard stdout, just retaining stderr, I get:

    identify -verbose corrupt.jpg > /dev/null
    

    Sample Output

    identify: Premature end of JPEG file `corrupt.jpg' @ warning/jpeg.c/JPEGWarningHandler/364.
    identify: Corrupt JPEG data: premature end of data segment `corrupt.jpg' @ warning/jpeg.c/JPEGWarningHandler/364.
    

    Alternatively, you could discard stderr too and simply look at the exit code (0=success, anything else=error):

    identify -regard-warnings -verbose corrupt.jpg > /dev/null 2>&1
    echo $?
    1
    

    whereas for a complete image:

    identify -regard-warnings -verbose image.jpg > /dev/null 2>&1
    echo $?
    0
    

    ImageMagick is installed on most Linux distros and is available for macOS/OSX and Windows.

提交回复
热议问题