PPM изображения в Android - PullRequest
       35

PPM изображения в Android

2 голосов
/ 18 июля 2011

Я пытаюсь открыть изображения .ppm (переносные изображения) в Android. Я расшифровал формат достаточно, чтобы создать это:

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

Я дохожу до того, что декодирую пиксели, но значения ascii для зеленого и синего значений даже для первого пикселя составляют 16-битное максимальное значение (65535 при использовании .read ()). Как вы можете видеть, я много чего пробовал, чтобы получить достойное соотношение цветов, но не повезло.

Когда я смотрю на значения в ppm, символы во втором и третьем полях выглядят странно. Кто-нибудь знает, где я сбился с пути? Ppm правильно открывается в фотошопе ...

Ответы [ 2 ]

2 голосов
/ 19 июля 2011

Мой код был довольно глупым, так как я не исследовал, что такое символ в Java. char в Java - не простой байт. Когда код модифицируется так, что он расходуется побайтово, он работает.

1 голос
/ 29 июля 2014

для тех, кто все еще борется с этим, вот функциональное решение, которое мне удалось создать, объединяя его с другим кодом, который я нашел в Интернете:

public static Bitmap ReadBitmapFromPPM2(String file) throws IOException {
    //FileInputStream fs = new FileInputStream(file);
    BufferedInputStream reader = new BufferedInputStream(new FileInputStream(new File(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();

    int width = Integer.valueOf(widths);
    int height = Integer.valueOf(heights);
    int[] colors = new int[width * height];

    byte [] pixel = new byte[3];
    int len = 0;
    int cnt = 0;
    int total = 0;
    int[] rgb = new int[3];
    while ((len = reader.read(pixel)) > 0) {
        for (int i = 0; i < len; i ++) {
            rgb[cnt] = pixel[i]>=0?pixel[i]:(pixel[i] + 255);
            if ((++cnt) == 3) {
                cnt = 0;
                colors[total++] = Color.rgb(rgb[0], rgb[1], rgb[2]);
            }
        }
    }

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