Detecting whether an image is corrupted or broken

前端 未结 3 2012
有刺的猬
有刺的猬 2021-01-19 07:10

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

相关标签:
3条回答
  • 2021-01-19 07:59

    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++;
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-19 07:59

    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;
      }
    ?>
    
    0 讨论(0)
  • 2021-01-19 08:00

    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.

    0 讨论(0)
提交回复
热议问题