I need to programmatically check whether the image that the user has selected as his wallpaper on my app is broken or corrupted....... basically I provide user with the option to choose his own image as wallpaper. Now when the images loads, I just want to keep a check on whether it is somehow corrupt or not.......
Asked
Active
Viewed 1.2k times
5
-
http://stackoverflow.com/questions/1977871/check-if-an-image-is-loaded-no-errors-in-javascript – Māris Kiseļovs Mar 30 '12 at 07:13
-
1solutiion is here http://stackoverflow.com/questions/6568247/is-there-any-way-to-have-php-detect-a-corrupted-image – Jassi Oberoi Mar 30 '12 at 07:14
3 Answers
6
If instead you are looking for a PHP solution instead of a javascript solution (which the potential duplicates do not provide), you can use GD's getimagesize() in PHP and see what it returns. It will return false and throw an error when the provided image format is not valid.

objectified
- 262
- 1
- 2
5
Here is a PHP CLI script you can run on a directory full of images and it will log which files are corrupted based on an imagecreatefrom***()
test. It can just log the bad files or take action and delete them.
https://github.com/e-ht/literate-happiness
You can also plug it in to a database to take action on image paths that you may have stored.
Here is the meat of the function it uses:
$loopdir = new DirectoryIterator($dir_to_scan);
foreach($loopdir as $fileinfo) {
if(!$fileinfo->isDot()) {
$file = $fileinfo->getFilename();
$file_path = $dir_to_scan . '/' . $file;
$mime_type = mime_content_type($file_path);
switch($mime_type) {
case "image/jpg":
case "image/jpeg":
$im = imagecreatefromjpeg($file_path);
break;
case "image/png":
$im = imagecreatefrompng($file_path);
break;
case "image/gif":
$im = imagecreatefromgif($file_path);
break;
}
if($im) {
$good_count++;
}
elseif(!$im) {
$bad_count++;
}
}
}
-
This worked for me. In some cases, `getimagesize` threw errors that I couldn't catch, but this worked in all cases. Thank you. – HartleySan Aug 24 '19 at 13:40
4
This seems to work for me.
<?php
$ext = strtolower(pathinfo($image_file, PATHINFO_EXTENSION));
if ($ext === 'jpg') {
$ext = 'jpeg';
}
$function = 'imagecreatefrom' . $ext;
if (function_exists($function) && @$function($image_file) === FALSE) {
echo 'bad img file: ' . $image_file . ' ' . $function;
}
?>

mikeytown2
- 1,744
- 24
- 37
-
You have a typo at ```echo 'bad img file: ' . $image_file . ' ' . $function);``` – aki Sep 23 '15 at 07:39
-
*Use this instead: * `$function = 'imagecreatefrom' . strtolower($ext);` – David Refoua Oct 25 '17 at 14:03