【发布时间】:2026-01-24 15:00:01
【问题描述】:
我想我刚刚查明了问题所在,但我仍然不确定该怎么做。
我使用 Photoshop 创建了各种动画 gif,我想在我的 Java 应用程序中显示它们。使用 ImageIcon,其中一些会按应有的方式显示。那些具有相同帧速率的帧(例如每帧长 1 秒)。但是,具有不同帧速率(例如,一帧是 1 秒,另一帧是 0.5 秒,下一帧是 0.2)的 gif 似乎无法正确显示。一旦 gif 到达以秒为单位的帧,图像就会混乱。一些示例包括背景短暂改变颜色和一半图像消失,或者大部分图像消失但 gif 仍在动画中。
我很难表达,但我是否需要使用 ImageIcon 以外的其他东西来正确加载具有不同帧速率的 gif?喜欢 BufferedImage 的东西?
编辑:在下面添加了完整的代码。同样,它适用于具有相同帧速率的图像,但不适用于具有不同帧速率的图像。
here is the image that works fine
和here is the image that messes up
import java.awt.*;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
public class Creature extends JWindow {
public void initCreature() {
JPanel contentPane = (JPanel) getContentPane();
ImageIcon idleImage = new ImageIcon(getClass().getResource("img.gif"));
// Set window properties
getRootPane().putClientProperty("Window.shadow", false);
setBackground(new Color(0,0,0,0));
setAlwaysOnTop(true);
contentPane.setOpaque(false);
// Get size of user's screen
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
Rectangle screen = defaultScreen.getDefaultConfiguration().getBounds();
int taskbarheight = (int) (Toolkit.getDefaultToolkit().getScreenSize().height
- GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().getHeight());
int x = (int) screen.getMaxX() - idleImage.getIconWidth();
int y = (int) screen.getMaxY() - idleImage.getIconHeight() - taskbarheight;
JLabel imageLabel = new JLabel(idleImage);
setSize(idleImage.getIconWidth(), idleImage.getIconHeight());
contentPane.add(imageLabel);
setLocation(x, y);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
Creature cr = new Creature();
cr.initCreature();
}
});
}
}
【问题讨论】:
-
发布您的代码的最小示例以了解可能出现的问题。
-
添加到原始帖子。我开始认为我可能应该使用 ImageIcon 以外的其他东西
-
1) 为了尽快获得更好的帮助,请发帖 minimal reproducible example 或 Short, Self Contained, Correct Example。 2) 将行为不端的图像上传到图像共享网站并链接到它。
-
感谢安德鲁,再次修复了我的帖子并添加了完整的程序+图片链接。鉴于我经常潜伏在这里,我会想知道如何最好地发帖。
-
两个版本的帧速率似乎相同(一个在浏览器中看到,另一个在
JLabel中看到)。我猜我会说问题在于 PhotoShop 正在使用高级编码来确保只有 帧中发生变化的部分被更新。请注意,尽管 Java 支持特定的 文件类型,如 GIF、PNG 或 JPEG,但这并不意味着它正确理解每种文件类型的每种 编码 类型。一个更简单的图像,每次更改都会更改整个帧应该会更好,但字节数也会更大。
标签: java swing animated-gif frame-rate