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.......
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.......
Share Improve this question asked Mar 30, 2012 at 7:11 DilletanteDilletante 1,8914 gold badges19 silver badges18 bronze badges 2- stackoverflow.com/questions/1977871/… – Māris Kiseļovs Commented Mar 30, 2012 at 7:13
- 1 solutiion is here stackoverflow.com/questions/6568247/… – Jassi Oberoi Commented Mar 30, 2012 at 7:14
3 Answers
Reset to default 6If 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.
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;
}
?>