[英]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).
我正在读入数组 RGB 值(ppm 格式)。 I'm not sure what I'm doing wrong, but here's my code & pic (its supposed to be a red Lancia Stratos) :
我不确定我做错了什么,但这是我的代码和图片(它应该是红色的蓝旗亚 Stratos):
http://oi60.tinypic.com/20h91kk.jpg 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.在二维数组中,
i
是行的变化, j
是列的变化。 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.当您将第一个循环的循环条件设置为
k < height
,您表示这将通过更改行来完成。
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.当您将循环条件设置为
p < width
,对于第二个循环(嵌套在第一个循环中),您表示这将通过更改列来完成。
Thus, the (i, j) position of the point is actually in the form of (p, k) when using a Cartesian plane.因此,当使用笛卡尔平面时,点的 (i, j) 位置实际上是 (p, k) 的形式。 This commonly gets mixed up.
这通常会混淆。
So lastly, change the set RGB to: img.setRGB(p, k, col);
所以最后,将设置的 RGB 更改为:
img.setRGB(p, k, col);
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.