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 opt
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 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;
}
?>
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.