Bitmap Out Of Memory异常抛出新的OutOfMemoryException(e);

时间:2013-03-22 21:23:47

标签: android out-of-memory

我继承了这段代码,并试图弄清楚如何使它更有效,所以我不必抛出OutOfMemory异常。这适用于writeBitmap和readBitmap。

/**
 * Reads bitmap from the state file
 */
void readBitmap(Bitmap bitmap) throws OutOfMemoryException {
    byte[] buffer;
    try {
        buffer = new byte[file.length()];
    } catch (OutOfMemoryError e) {
        throw new OutOfMemoryException(e);
    }

    try {
        file.readBytes(buffer, 0, 0, buffer.length);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Buffer byteBuffer = ByteBuffer.wrap(buffer);

    try {
        bitmap.copyPixelsFromBuffer(byteBuffer);
    } catch (Exception e) {

    }
}

1 个答案:

答案 0 :(得分:1)

您可以保存压缩位图。它会使你不需要一个中间字节缓冲区。只需将压缩格式调整为您想要的格式即可。您还可以使用创建的内存文件的大小。

   public void writeBitmap(Bitmap bitmap, int id) throws OutOfMemoryException {
        final int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();

        try {
            file = new MemoryFile("file" + id, bitmapSize);
            FileOutputStream out = file.getOutputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        size.x = bitmap.getWidth();
        size.y = bitmap.getHeight();
    }