5

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.......

Dilletante
  • 1,801
  • 4
  • 19
  • 18

3 Answers3

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