bash detect corrupted images

detect corrupted images

If you have a need to detect corrupted images, you can easily do it with command line utility “identify“.

Find and install it on your Linux machine:

[root@linux ~]# which identify
/usr/bin/which: no identify in (/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin)
[root@linux ~]# yum install -y ImageMagick &>/dev/null
[root@linux ~]# which identify
/bin/identify
[root@linux ~]# 

Now let’s perform some tests. Get an image – download one successfully and interrupt download process on another attempt:

[root@linux ~]# wget -O Tux_good.png https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Tux.svg/865px-Tux.svg.png
--2020-10-07 11:18:16--  https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Tux.svg/865px-Tux.svg.png
Resolving upload.wikimedia.org (upload.wikimedia.org)... 91.198.174.208, 2620:0:862:ed1a::2:b
Connecting to upload.wikimedia.org (upload.wikimedia.org)|91.198.174.208|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 149878 (146K) [image/png]
Saving to: 'Tux_good.png'

100%[==============================================================================================================================>] 149,878     --.-K/s   in 0.1s

2020-10-07 11:18:16 (1.24 MB/s) - 'Tux_good.png' saved [149878/149878]

[root@linux ~]# wget -O Tux_bad.png --limit-rate=30k https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Tux.svg/865px-Tux.svg.png
--2020-10-07 11:19:08--  https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Tux.svg/865px-Tux.svg.png
Resolving upload.wikimedia.org (upload.wikimedia.org)... 91.198.174.208, 2620:0:862:ed1a::2:b
Connecting to upload.wikimedia.org (upload.wikimedia.org)|91.198.174.208|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 149878 (146K) [image/png]
Saving to: 'Tux_bad.png'

15% [==================>                                                                                                            ] 23,457      30.0KB/s             ^C
[root@linux ~]# ls -lh Tux_*
-rw-r--r-- 1 root root  31K Oct  7 11:19 Tux_bad.png
-rw-r--r-- 1 root root 147K Aug  3 17:39 Tux_good.png
[root@linux ~]# 

You can now let “identify” do the magic and check its exit code. Don’t forget to use “-verbose” option – otherwise it will not show non-zero exit code for our test (when image is incomplete):

[root@linux ~]# identify -verbose Tux_good.png &>/dev/null; echo $?
0
[root@linux ~]# identify -verbose Tux_bad.png &>/dev/null; echo $?
1
[root@linux ~]#