我正在尝试调整ImageIcon的大小并在GridBagLayout JPanel中使用它。它确实调整了大小......但它仍然以全尺寸显示。因此,您在较大的图像内部有一个调整大小的图像。任何人都看到下面的代码明显错误?谢谢!
public CharacterPage(WikiDB db) throws IOException {
super("Character Page");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(new Dimension(1000,1000));
rootPanel.setLayout(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
rootPanel.setSize(new Dimension(500,500));
searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
BufferedImage img1 = null;
for (int x = 0; x < characterImages.size(); x++){
String imageURL = "http://cosplayidol.otakuhouse.com/wp-
content/uploads/2012/06/s-1-1.jpg"
try
{
URL url1 = new URL(imageURL);
URLConnection conn1 = url1.openConnection();
conn1.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
InputStream in1 = conn1.getInputStream();
img1 = ImageIO.read(in1);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
Graphics2D g2 = img1.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img1, 0,0,100, 100, null);
g2.dispose();
ImageIcon newIcon = new ImageIcon(img1);
c.fill = GridBagConstraints.HORIZONTAL;
JLabel cIcon = new JLabel(newIcon);
c.gridx = 0;
c.gridy = 6;
rootPanel.add(cIcon,c);
}
});
setContentPane(rootPanel);
pack();
setVisible(true);
}
答案 0 :(得分:3)
Graphics2D g2 = img1.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img1, 0, 0, 100, 100, null);
g2.dispose();
应该是这样的:
int w = 100;
int h = 100;
// create an image of the appropriate size!
BufferedImage img2 = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = img2.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img1, 0, 0, w, h, null);
g2.dispose();
答案 1 :(得分:0)
这些线将调整后的图像重新绘制在原始图像上:
Graphics2D g2 = img1.createGraphics();
g2.drawImage(img1, 0,0,100, 100, null);
绘制从rootPanel本身创建的图形。