逐行加载图像Java

时间:2016-06-06 19:38:49

标签: java arrays image loading line-by-line

所以这听起来很荒谬,但我正在开展一个项目,我故意想要减慢图像的加载速度,以便逐行加载。无论如何我能做到吗?我目前在ImagePane中有图像,它只是JPanel的扩展名:

public ImagePane() {
        initComponents();
        image = null;
        //this.setAutoscrolls(true);
    }
    public void setImage(String path) throws IOException {
        image = ImageIO.read(getClass().getResource(path));
    }

    @Override
    public void paintComponent(Graphics g)
    {
        //Graphics2D g2 = (Grahpics2D)g;
        g.drawImage(image, 0,0, this);
    }

在我的窗口中,我试图将其显示为:

ImagePane image = new ImagePane();
try {
    image.setImage("netscapelogo2.png");
}
catch (IOException e) {
    System.out.print("Failed to Set");
    e.printStackTrace();
}
//jScrollPane1.add(image);
jScrollPane1.setViewportView(image);

我想我需要有人改变我的paintComponent方法才能做到这一点,但我不确定该怎么做。

1 个答案:

答案 0 :(得分:2)

此解决方案使用预览I would simulate that the image is loading line by line by uncovering it gradually. – rodrigoap,因此图像会立即加载,只会显示,因为它会逐行读取!

解决方案是创建一个线程并让线程工作......

Runnable r = new Runnable(){

    @Override
    run(){
        for(int i = 0; i < image.getHeight(); i++){
            // wait 100ms to 'slow down'
            Thread.sleep(100)// surround with try/catch, it may throw an exception
            line = line + 1; //increase amount of visible lines
            repaint(); //update the panel
        }
    }
}

//i don't know when you want to start the animation
new Thead(r).start(); //so trigger at free will

当您绘制图像时,您只绘制了一定数量的线条,而不是整个图像......

@Override
public void paintComponent(Graphics g)
{
    super(g);
    int w = image.getWidth();
    int h = image.getHeight();
    g.drawImage(image, 0,0, w, line, 0,0,w,h,this);
}

drawImage方法有点奇怪,请参阅docu以获得进一步的帮助

当然,您需要在某个地方定义private int line = 0;