我正在尝试使用 ImageView 显示图片文件, 虽然我知道我可以直接将文件解码为位图, 但我必须对它做一些其他的事情,所以我只能选择 byte[]。
代码如下所示:
File file = new File(getRealPathFromURI(Uri.parse(ImgUri)));
byte[] beforeData = new byte[(int) file.length()];
try {
FileInputStream fis = new FileInputStream(file);
int detectEnd = 0;
while (detectEnd != -1){detectEnd = fis.read(beforeData, 0, 1024);}
Bitmap b_t = BitmapFactory.decodeByteArray(beforeData, 0, beforeData.length);
editImgView.setImageBitmap(b_t);
} catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
我试着测试一下我是否正确阅读了图片, 所以我解码成位图然后尝试显示它, 但它根本不显示任何图片。
我对 FileInputStream 有什么误解吗? 附言。我用log.i查看发现beforeData的长度是正常的, 但是里面的数据只得到: [B@40c4b110 , 这不像图片的数据。
提前致谢, 解决。
糟糕,谢谢你 siliconeagle, 我忘了考虑那部分......(一开始我就做了) 但是,似乎这不是主要问题所在... 现在循环看起来像:
while (pos < beforeData.length){
read = fis.read(beforeData, pos, 1);
pos += read;
}
我知道这是愚蠢和虚假的, 但是这个 block 中的代码应该可以正常工作,对吧? 但是,我仍然无法在我的 ImageView 中看到任何图片。
另附: 该文件的路径位于/mnt/sdcard/DCIM/Camera/1310368442822.jpg, 大小 1485847 字节, 大小会带来什么麻烦吗?
最佳答案
您每次循环只将数据读入数组的前 1024 个字节。
fis.read(beforeData, 0, 1024);
你必须维护一个位置计数器 (int pos) 并使用另一个变量 (int read) 来检测 -1
int read=0;
int pos=0;
while (read!=-1) {
read= fis.read(beforeData, pos, 1024);
pos+=read;
}
确保您也关闭文件 (fis.close())...
最好的方法是:
File tmpImgFile = new File("/path");
BitmapFactory.decodeFile(tmpImgFile.getAbsolutePath());
关于android - 使用字节数组读入文件,然后显示在ImageView (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6649671/