如何在Android中检测图像文件

3

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

当我将.jpg扩展名更改为.xyz之类的东西时,安卓无法将此图像文件识别为图像文件,并且无法打开相同的文件。甚至相册也无法检测到此文件。

现在如何使安卓将此文件识别为图像文件?

-谢谢&问候, Manju


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

2

将文件路径转换为URI:

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

然后,使用内容解析器获取文件MIME类型:

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

这是标准的推荐方法。希望能帮到你。

尝试了上面的例子,但返回 null。我将一个有效的 .jpg 文件重命名为 .xyz 并复制回设备,尝试解码相同的文件也返回 null。 - Manju
@Manju,我没有听懂你的意思。你能再解释一下吗? - sanjeev mk
嗨,Sanjeev,我已经在上面粘贴了示例代码供您参考。我已经通过扩展名.icy将从相机创建的.jpg文件复制到另一个文件,并尝试在画廊中打开该文件或尝试通过代码获取相同文件的位图信息,但返回null。 - Manju

0

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

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。 - Manju
@nikvs,我已经更新了我的评论,并附上了这个示例代码的输出结果,你对此有什么建议吗? - Manju
尝试使用"Environment.getExternalStorageDicrectory()"代替"/storage/emulated"。 - nikvs
@nikvs,从日志中,12-20 11:28:53.761:D/Manju ==>(9171):图像文件:/storage/emulated/0/JP2/20131219_120037_16.icy,存在。 - Manju
文件已经存在,还需要使用“Environment.getExternalStorageDirectory()”而不是“/storage/emulated”吗? - Manju
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接