Pooks
Pooks

Reputation: 2585

What is the best way to write an int array (image data) to file

I have a large int array containing image data in the format ARGB (alpha, R, G and B channels, 1 byte each). I want to save it to file in onPause() to be able to reload it when the app is restarted. What do you think is the best way to do that?

I found the following methods:

All these methods seem quite wasteful so there is probably another, better way. Possibly even a way to use image compression to reduce the size of the file?

Upvotes: 0

Views: 3062

Answers (2)

user207421
user207421

Reputation: 310985

None of those. Some of them don't even make sense.

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));

then call dos.writeInt() as many times as necessary, then close dos. The buffer will take away most of the pain.

Or else create an IntBuffer and use FileChannel.write(), but I've never been able to figure out how that works in the absence of an IntBuffer.asByteBuffer() method. Or else create a ByteBuffer, take it as an IntBuffer via asIntBuffer(), put the data in, then adjust the ByteBuffer's length, which is another missing piece of the API, and again use FileChannel.write(ByteBuffer).

Upvotes: 3

Nikolay Ivanov
Nikolay Ivanov

Reputation: 8935

From my point of view you can also use android specific storages

  1. Use database/content provider for storing image data
  2. Use out Bundle in onSaveInstance method

If your still want to write to a file you can use following NIO based code:

static void writeIntArray(int[] array) throws IOException {
    FileOutputStream fos = new FileOutputStream("out.file");
    try {
        ByteBuffer byteBuff = ByteBuffer.allocate((Integer.SIZE / Byte.SIZE) * array.length);
        IntBuffer intBuff = byteBuff.asIntBuffer();
        intBuff.put(array);
        intBuff.flip();
        FileChannel fc = fos.getChannel();
        fc.write(byteBuff);
    } finally {
        fos.close();
    }
}

Upvotes: 3

Related Questions