【问题标题】:how to detect image file in android如何在android中检测图像文件
【发布时间】:2013-12-19 12:19:55
【问题描述】:

我需要将现有图像文件扩展名更改为其他内容并保存在设备上。

当我将 .jpg 的扩展名更改为 .xyz 之类的东西时,这个相同的图像文件不会被 android 检测为图像文件并且无法打开它。连画廊都没有检测到这个文件。

现在如何让android将此文件检测为图像文件?

-谢谢和问候, 馒头

【问题讨论】:

  • 您可以使用模式匹配。 file.getAbosutePath().endWith(".jpg|.xyz)
  • 请添加一些代码,以便我们查看您使用了什么。
  • 我将有效的 .jpg 文件重命名为 .xyz 并复制回设备并尝试在无法检测文件类型的图库中查看相同的文件。我试过 Bitmap.decode 但它返回 null

标签: android android-gallery


【解决方案1】:

将文件路径转换为 ​​URI:

    File file = new File(path + File.pathSeparator + filename);
    Uri uri = Uri.fromFile(file);

然后,使用 Content Resolver 获取文件的 MIME 类型:

    String mimeType = getContentResolver().getType(uri);

这是标准的推荐方法。

希望对您有所帮助..

【讨论】:

  • 试过上面的例子,但它返回 null,我将一个有效的 .jpg 文件重命名为 .xyz 并复制回设备并尝试解码相同的返回 null
  • @Manju 不明白你的意思。你能解释一下吗?
  • 嗨 Sanjeev,上面粘贴了示例代码供您参考。我已将相机创建的 .jpg 文件复制到另一个扩展名为 .icy 的文件中,并尝试在图库中打开该文件或尝试通过返回 null 的代码获取相同所述文件的位图信息。
【解决方案2】:

您可以通过解码到位图来检查,只有图像文件可以解码为位图。

Bitmap bmp = BitmapFactory.decodeFile(filePath);
if(null!=bmp)
{
//image file
} else {
not image file.
}

下面是我的代码

String fileName="/storage/emulated/0/JP2/20131219_120037_16.icy";
   File file = new File(fileName);

   if(file!=null && file.exists()){
    Log.d("Manju ==>","image file: "+fileName+", does exist");
   }else{
    Log.e("Manju ==>","image file: "+fileName+", doesnot exist !!");
   }

    Uri uri=Uri.fromFile(file);
    String mimeType = getContentResolver().getType(uri);
    Log.d("Manju ==>","mime Type: "+mimeType);

    Bitmap bmp = BitmapFactory.decodeFile(fileName);
    if(null!=bmp){
       //image file
    Log.d("Manju ==>","image file valid, height: "+bmp.getHeight()+", width: "+bmp.getWidth());
    } else {
    Log.d("Manju ==>","image file invalid !!!");
    }

【讨论】:

  • 我试过上面的例子,但失败了!! bmp 为 NULL,但图像文件有效。我将有效的 .jpg 文件重命名为 .xyz 并复制回设备并尝试解码相同的返回 null
  • 您是否仔细检查了文件路径。如果错误,那么 bmp 也会为空。
  • 这个日志是"Log.d("Manju ==>","image file: "+fileName+", does exist");"显示?如果显示,您可以尝试 Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
  • 12-20 11:28:53.761: D/Manju ==>(9171): 图像文件: /storage/emulated/0/JP2/20131219_120037_16.icy, 确实存在 12-20 11: 28:53.761:D/Manju ==>(9171):mime 类型:空 12-20 11:28:53.766:D/Manju ==>(9171):图像文件无效!!! 12-20 11:28:53.766: D/Manju ==>(9171): BitmapFactory.decodeFile 之后,高度:-1,宽度:-1,类型:null
  • @nikvs,我已经用这个示例代码的输出更新了我的 cmets,你有什么建议吗?
猜你喜欢
  • 2018-10-07
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2015-01-13
  • 1970-01-01
相关资源
最近更新 更多