简体   繁体   中英

How to draw image using RGB?

I've got semi-working code here. I'm getting a bad draw, the image doesn't draw correctly. I'm reading into an array RGB values (ppm format). I'm not sure what I'm doing wrong, but here's my code & pic (its supposed to be a red Lancia Stratos) :

http://oi60.tinypic.com/20h91kk.jpg

package ppmHomework;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ReadImage {

public ReadImage() {

}

public static void main(String[] args) throws FileNotFoundException {

    int width, height, maxRGB;

    File file = new File("ppmImage.ppm");

    Scanner kb = new Scanner(file);
    kb.next();
    width = kb.nextInt();
    height = kb.nextInt();
    maxRGB = kb.nextInt();
    JFrame frame;
    BufferedImage img;

    int[] arrayImage = new int[width * height * 3];

    int j=0;
    while (kb.hasNextInt()) {
        arrayImage[j] = kb.nextInt();
        j++;
    }

    img = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
    int i = 0;
    for (int k = 0; k < width; k++) {
        for (int p = 0; p < height; p++) {
            System.out.println(arrayImage[i] + " " + arrayImage[i+1] + " " + arrayImage[i+2] + " " + i); 
                int col = new Color(arrayImage[i], arrayImage[i+1], arrayImage[i+2]).getRGB();
                img.setRGB(k, p, col);
                i+=3;
            }

        }
    frame = new JFrame("WINDOW");
    frame.setVisible(true);

    frame.add(new JLabel(new ImageIcon(img)));

    frame.pack();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);


}

} Any help is much appreciated...thanks

The problem exists with the way data is stored in a 2D array. In a 2D array, i is a change of rows and j is a change of columns. We can then see the following:

      i
  +---------------> Change in columns
  | 4   7   8  10
  | 5   1  23   4
j | 8   2   1   0
  | 4   6   8   1
  |
  V Change in rows

When you set the loop condition to k < height for the first loop, you are stating that this will be done through the changing of rows.

When you set the loop condition to p < width , for the second loop (nested in the first), you are stating that this will be done through the changing of columns.

Thus, the (i, j) position of the point is actually in the form of (p, k) when using a Cartesian plane. This commonly gets mixed up.

So lastly, change the set RGB to: img.setRGB(p, k, col); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM