Read images byte by byte from android internal sto

2019-09-14 18:11发布

I'm trying to display images from android internal storage, I have only 4images(the images are screen shots taked before), I display these images in a GridView, it works, but it takes too much time, this is my code :

FileInputStream fis = null;
DataOutputStream outWriter = null;
ByteArrayOutputStream bufStream = null;
String imageFile;
int occurence;
for (int i=0; i<4; i++) {
    try {
        occurence = i+1;
        imageFile = "preview"+occurence+".png";
        fis = openFileInput(imageFile);
        bufStream = new ByteArrayOutputStream();
        outWriter = new DataOutputStream(bufStream);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    int ch;
    byte[] data = null;
    try {
        **while((ch = fis.read()) != -1)
            outWriter.write(ch);**
        outWriter.close();
        data = bufStream.toByteArray();
        bufStream.close();
        fis.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }  
    favorPreviews.add(BitmapFactory.decodeByteArray(data, 0, data.length)) ;
}

As you can see, I'm using FileInputStream to read them, but that reads the files byte by byte in this loop :

while((ch = fis.read()) != -1)
    outWriter.write(ch);

And it takes too much time, is anyone know a faster way to read these images?

标签: android file
2条回答
叼着烟拽天下
2楼-- · 2019-09-14 18:47

To be faster is indicated to reduced the image size. It can be done using the Bitmap decodeFile (String pathName, BitmapFactory.Options opts)

Look this example:

public Bitmap getReducedBitmap(String path) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inSampleSize=4; // reduced the image to 1/4 of the orignal size
    return BitmapFactory.decodeFile(path, opt);
}
查看更多
\"骚年 ilove
3楼-- · 2019-09-14 18:54

Use BitmapFactory.decodeFile(String) instead. Then all of this file reading is handled for you.

查看更多
登录 后发表回答