[英]Draw image using rectangles
I wrote a program that reads an image from command line and want to read each pixel to draw a rectangle of the respective colour to "recreate" the image from rectangles. 我编写了一个程序,该程序从命令行读取图像,并希望读取每个像素以绘制相应颜色的矩形,以从矩形“重新创建”图像。
However, although the rectangles have the correct size, every pixel seems to be black. 但是,尽管矩形的大小正确,但每个像素似乎都是黑色的。 At least, what I see in the output panel is a black picture that has the same size as the input picture. 至少,我在输出面板中看到的是一张与输入图片大小相同的黑色图片。
class AppDrawPanel extends JPanel {
private BufferedImage bi;
/* ... */
public void loadAPPImage( String s ) throws IOException{
bi = ImageIO.read(new File(s));
}
@Override
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D) g;
int w = bi.getWidth();
int h = bi.getHeight();
for( int x = 0; x < w; x++){
for ( int z = 0; z < h; z++ ){
Color c = new Color(bi.getRGB(x, z));
super.setForeground(c);
g2.fillRect(x, z, 3, 3);
}
}
}
}
And the main function: 和主要功能:
public static void main( String[] args ) throws IOException{
/* ... */
AppDrawPanel draw = new AppDrawPanel();
draw.loadAPPImage(args[0]);
frame.add(draw);
/* ... */
}
where /* ... */
represents code that has nothing to do with drawing the rectangles or reading the image. /* ... */
表示与绘制矩形或读取图像无关的代码。
In this related example , the width and height of each pixel is scaled by an arbitrary factor of 10. The method drawImage()
then scales the image to the component's preferred size. 在此相关示例中 ,每个像素的宽度和高度都以10的任意因子缩放。方法drawImage()
然后将图像缩放到组件的首选大小。 As an exercise, override getPreferredSize()
to return an appropriate dimension: 作为练习,重写getPreferredSize()
以返回适当的尺寸:
new Dimension(imgW * 10, imgH * 10);
Also consider making the arbitrary factor a class-level property. 还可以考虑使任意因子成为类级别的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.