【发布时间】:2011-12-10 14:56:31
【问题描述】:
原问题:
这个方法应该将显示在 JFrame 上的图像逐渐更改为另一个图像。但是,如果没有某种方法可以减慢它的速度,它似乎只是从一个图像变为新图像。为了减慢它的速度,我放入了一个 Thread.sleep(1000) 这样更改不会立即发生。然而,有了这条线,我的程序就完全冻结了。没有错误信息,什么都没有。谁能帮帮我?建议一个更好的方法来减慢它,或者如何解决这个问题。
澄清一下:int k 是变化的渐进步骤数。 k = 1 将是一个瞬间的变化。任何更大的变化都是渐进的。 int l 同时控制每张图片的显示比例。
public void morphImg(int width, int height, BufferedImage morphImage, int k) {
//creates new image from two images of same size
BufferedImage image2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
//get color from original image
Color c = new Color(image.getRGB(i, j));
//get colors from morph image
Color c2 = new Color(morphImage.getRGB(i, j));
for (int l = 1; l <= k; l++) {
//gets colors at different stages
int r = ((k-l)*c.getRed()/k) + (l*c2.getRed()/k);
int g = ((k-l)*c.getGreen()/k) + (l*c2.getGreen()/k);
int b = ((k-l)*c.getBlue()/k) + (l*c2.getBlue()/k);
Color newColor = new Color(r, g, b);
//set colors of new image to average of the two images
image2.setRGB(i, j, newColor.getRGB());
//display new image
try {
imageLabel.setIcon(new ImageIcon(image2));
Thread.sleep(1000);
}
catch (InterruptedException e){
System.out.println("Exception caught.");
}
}
}
}
//sets modified image as "original" for further manipulation
setImage(image2);
}
更新的代码:使用计时器也会导致程序冻结...我没有使用它吗?
public void morphImg(int width, int height, BufferedImage morphImage, int k) {
//creates new image from two images of same size
final BufferedImage image2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int l = 1; l <= k; l++) {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
//get color from original image
Color c = new Color(image.getRGB(i, j));
//get colors from morph image
Color c2 = new Color(morphImage.getRGB(i, j));
//gets colors at different stages
int r = ((k-l)*c.getRed()/k) + (l*c2.getRed()/k);
int g = ((k-l)*c.getGreen()/k) + (l*c2.getGreen()/k);
int b = ((k-l)*c.getBlue()/k) + (l*c2.getBlue()/k);
Color newColor = new Color(r, g, b);
//set colors of new image to average of the two images
image2.setRGB(i, j, newColor.getRGB());
//display new image
imageLabel.setIcon(new ImageIcon(image2));
final Timer t = new Timer(500,null);
t.setInitialDelay(500);
t.start();
}
}
}
//sets modified image as "original" for further manipulation
setImage(image2);
}
【问题讨论】:
-
你知道你总共在睡觉 (width * height * k) 秒吗?对于 k 设置为 10 的 256x256 图像,您的代码需要 7 天才能运行。
标签: java try-catch sleep freeze bufferedimage