检测图像是否损坏或损坏

问题描述:

我需要以编程方式检查用户在我的应用程序上选择作为墙纸的图像是否损坏或损坏....... 基本上我向用户提供了选项选择他自己的图像作为墙纸。现在,当图像加载,我只是想保持它是否是某种损坏或不检查.......检测图像是否损坏或损坏

+0

http://*.com/questions/1977871/check-if-an-image-is-loaded-no-errors-in- javascript – 2012-03-30 07:13:26

+1

solutiion is here http://*.com/questions/6568247/is-there-any-way-to-have-php-detect-a-corrupted-image – 2012-03-30 07:14:34

相反,如果你正在寻找一个PHP的解决方案,而不是一个JavaScript解决方案(其中电位重复项不提供),您可以在PHP中使用GD的getimagesize()并查看返回结果。当提供的图像格式无效时,它将返回false并引发错误。

+0

图像已损坏,但图像大小仍然存在。 – Gulshan 2017-11-01 07:11:05

这似乎适用于我。

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

你在'''echo'bad img file:'有错字。 $ image_file。 ''。 $ function);''' – aki 2015-09-23 07:39:07

+0

*用这个代替:*'$ function ='imagecreatefrom'。用strtolower($ EXT);' – 2017-10-25 14:03:30

这里是一个PHP CLI脚本,你可以在一个完整的图像的目录中运行,它会记录哪些文件是基于一个imagecreatefrom***()测试损坏。它只能记录坏文件或采取行动并删除它们。

https://github.com/e-ht/literate-happiness

您也可以将其插入到数据库承担,你可能已经存储图像路径行动。

这里是它采用了功能的肉:

$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++; 
     } 
    } 
}