【问题标题】:Know if a file is a image in Java/Android知道文件是否是 Java/Android 中的图像
【发布时间】:2012-03-03 22:07:09
【问题描述】:

给定一个文件路径,知道该文件是否是 Java(Android) 中的图像(任何类型)的最简单方法是什么?谢谢

【问题讨论】:

    标签: java android image


    【解决方案1】:

    您可以尝试使用此代码进行更准确的检查。

      public static boolean isImageFile(String path) {
            String mimeType = URLConnection.guessContentTypeFromName(path);
            boolean b = mimeType != null && mimeType.startsWith("image");
             if(b){
                 return BitmapFactory.decodeFile(path) != null;
             }
    
            return false;
        }

    【讨论】:

      【解决方案2】:

      试试这个代码段

      public static boolean isViewableImage(String name) {
          String suffix = name.substring(name.lastIndexOf('.') + 1).toLowerCase();
          if (suffix.length() == 0)
              return false;
          if (suffix.equals("svg"))
              // don't support svg preview
              return false;
      
          String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix);
          if (mime == null)
              return false;
          return mime.contains("image");
      }
      

      【讨论】:

        【解决方案3】:
        public static boolean isImage(File file) {
            if (file == null || !file.exists()) {
                return false;
            }
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getPath(), options);
            return options.outWidth != -1 && options.outHeight != -1;
        }
        

        【讨论】:

        • @MicroR ,如果您设置 options.inJustDecodeBounds = true; 比 BitmapFactory 将不会解码整个图像的数据,而只会解码图像的元数据。如果文件是有效图像,则BitmapFactory 将解析元数据并填充options.outWidth 和options.outHeight。这些字段将包含图像的宽度和高度。如果发生解码错误,字段将包含 -1。请参阅文档developer.android.com/intl/ru/reference/android/graphics/…
        【解决方案4】:

        有一些外部工具可以帮助您做到这一点。查看JMimeMagic 和JMagick。您也可以尝试使用 ImageIO 类读取文件,但这可能代价高昂且并非完全万无一失。

        BufferedImage image = ImageIO.read(new FileInputStream(new File(..._)));
        

        这个问题已经在 SO 上被问过几次了。请参阅有关同一主题的这些附加主题:

        Check if a file is an image

        How to check a uploaded file whether it is a image or other file?

        【讨论】:

        • 这在内存方面非常非常糟糕,并且会检查很多图像。这很容易导致 OutOfMemoryError
        猜你喜欢
        • 1970-01-01
        • 2010-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-07
        • 1970-01-01
        • 2017-10-05
        • 1970-01-01
        相关资源
        最近更新 更多