开发者

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

开发者 https://www.devze.com 2023-04-07 06:19 出处:网络
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 i开发者_如何学J

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 i开发者_如何学JAVAs restarted. What do you think is the best way to do that?

I found the following methods:

  • Convert the int array to a byte array manually (see here) and then use a FileOutputStream to output the byte array.

  • Wrap the array into a java.nio.IntBuffer and then write the object to file using java.io.ObjectOutputStream.writeObject().

  • Write each element one at a time using java.io.ObjectOutputStream.writeInt().

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?


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();
    }
}


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消