Search code examples
androidimageppm

PPM Images in Android


I'm trying to open .ppm images (Portable pixmaps) in Android. I've deciphered the format enough to create this:

public static Bitmap ReadBitmapFromPPM(String file) throws IOException
{
    //FileInputStream fs = new FileInputStream(file);
    BufferedReader reader = new BufferedReader(new FileReader(file));
    if (reader.read() != 'P' || reader.read() != '6')
        return null;
    reader.read(); //Eat newline
    String widths = "", heights = "";
    char temp;
    while ((temp = (char)reader.read()) != ' ')
    widths += temp;
    while ((temp = (char)reader.read()) >= '0' && temp <= '9')
    heights += temp;
    if (reader.read() != '2' || reader.read() != '5' || reader.read() != '5')
        return null;
    reader.read(); //Eat the last newline
    int width =  Integer.parseInt(widths);
    int height = Integer.parseInt(heights);
    int[] colors = new int[width*height];

   //Read in the pixels
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            char[] pixel = new char[3];
            reader.read(pixel);
            /*
            int red = reader.read();
            int green = reader.read();
            int blue = reader.read();

            byte r = (byte)red;
            byte g = (byte)green;
            byte b = (byte)blue;*/
            colors[y*width + x] =   //(255 << 24) | //A
                                    (pixel[0]&0x0ff << 16) | //R
                                    (pixel[1]&0x0ff << 8)  | //G
                                    (pixel[2]&0x0ff);       //B
        }
    }

    Bitmap bmp = Bitmap.createBitmap(colors, width, height, Bitmap.Config.ARGB_8888);

I get to the point where I'm decoding the pixels, but the ascii values of the green and blue values for even the first pixel are 16 bit max value (65535 when using .read()). As you can see I've tried a lot of things to drill down to a decent value for the colors, but no luck.

When I look at the values in the ppm the characters in the second and third fields are strange. Does anyone know where I'm going astray here? The ppm opens properly in photoshop...


Solution

  • My code was rather foolish since I didn't research what a char in Java actually was. char in Java is not a simple byte. When the code is modified to consume byte by byte it works.