Implementing file saving

When the MIDlet draws on the screen, it actually draws on an internal buffer image at the same time. To save the image, you must read the RGB data from the buffer and output it to a file.

A suitable file format that can be easily implemented in Java ME is the BMP image format. It has a simple header, followed by the image data in an RGB format "upside-down", meaning that the data starts from the lower left corner of the image. For more information about the details of the BMP format, see BMP file format on Wikipedia.

The following code snippet shows how the RGB data is written to a file:

    public void writeImageToFile(OutputStream filestream) throws IOException {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        createFileHeader(bout);
        createInfoHeader(bout);
        int y;
        int i;
        int pad;
        byte rgb[] = new byte[3];
        int[] argb = new int[biWidth * biHeight];
        pad = 4 - ((biWidth * 3) % 4);
        if (pad == 4) //if 4 we dont need any
        {
            pad = 0;
        }

        image.getRGB(argb, 0, biWidth, 0, 0, biWidth, biHeight);
        for (y = (biHeight - 1); y >= 0; y--) {
            for (int x = 0; x <= (biWidth - 1); x++) {
                rgb[0] = (byte) (argb[y * biWidth + x] & 0x000000FF);//blue
                rgb[1] = (byte) ((argb[y * biWidth + x] & 0x0000FF00) >> 8);//green
                rgb[2] = (byte) ((argb[y * biWidth + x] & 0x00FF0000) >> 16);//red
                bout.write(rgb);
            }
            for (i = 1; i <= pad; i++) {
                bout.write(0x00);
            }
        }
        filestream.write(bout.toByteArray());
        filestream.flush();
    }

The file saving is done in a separate thread, and while it is running, a loading notification is shown to the user.