使用矩形绘制图像

时间:2014-06-29 09:34:05

标签: java image swing

我编写了一个程序,它从命令行读取图像,并希望读取每个像素以绘制相应颜色的矩形,以“重新创建”矩形图像。

然而,尽管矩形具有正确的尺寸,但每个像素似乎都是黑色的。至少,我在输出面板中看到的是黑色图片,其大小与输入图片相同。

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

主要功能:

    public static void main( String[] args ) throws IOException{         
        /* ... */

        AppDrawPanel draw = new AppDrawPanel();
        draw.loadAPPImage(args[0]);
        frame.add(draw);        
        /* ... */
    } 

其中/* ... */表示与绘制矩形或读取图像无关的代码。

1 个答案:

答案 0 :(得分:3)

在此相关example中,每个像素的宽度和高度按任意因子10缩放。方法drawImage()然后将图像缩放到组件的首选大小。作为练习,覆盖getPreferredSize()以返回适当的维度:

new Dimension(imgW * 10, imgH * 10);

还要考虑将任意因子设为类级属性。