[英]Re sizing an image on a jLabel
I trying to re size an image on a jLabel in java, the snippet of the code which is not working is given below: 我试图在java中的jLabel上调整图像大小,下面给出了无效的代码片段:
ImageIcon imgThisImg = new ImageIcon(rs.getString("PictureURL"));
Image image=null;
image=jLabel2.createImage(120, 50);
ImageIcon imi=new ImageIcon(image);
jLabel2.setIcon(imi);
When i run it i get nothing on my jlabel. 当我运行它时,我的jlabel上什么都没有。 In fact if i run the code below it works fine. 事实上,如果我运行下面的代码,它工作正常。 The thing is that i want a scaled down image: 问题是我想要缩小图像:
ImageIcon imgThisImg = new ImageIcon(rs.getString("PictureURL"));
jLabel2.setIcon(imgThisImg);
I cant find where i am wrong. 我找不到我错的地方。 Please suggest me any ideas how should i go about it. 请告诉我任何想法我应该怎么做。
Thanks 谢谢
Please see below a better solution for re-scaling an image. 请参阅下面的重新缩放图像的更好解决方案。 In the code below, newImage
is the rescaled image. 在下面的代码中, newImage
是重新缩放的图像。
BufferedImage image = ImageIO.read(imageFile);
BufferedImage newImage = new BufferedImage(newWidth, newHeight, image.getType());
Graphics2D g2 = newImage.createGraphics();
g2.drawImage(image, 0, 0, newWidth, newHeight, null);
g2.dispose();
Here is code for a rendering component that might give you some tips. 这是一个渲染组件的代码,可能会给你一些提示。
class PaintCommandListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean hasFocus) {
Component c = super.getListCellRendererComponent(list, value, index, isSelected, hasFocus);
if (c instanceof JLabel && value instanceof PaintCommand) {
JLabel l = (JLabel)c;
PaintCommand pc = (PaintCommand)value;
try {
BufferedImage bi = pc.getUndoImage();
double w = bi.getWidth();
double ideal = 200d;
double ratio = w/ideal;
int aw = (int)(w/ratio);
int ah = (int)(bi.getHeight()/ratio);
BufferedImage bj = new BufferedImage(
aw,ah,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bj.createGraphics();
g.drawImage(bi, 0, 0, aw, ah, null);
g.dispose();
l.setIcon(new ImageIcon(bj));
l.setText("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return c;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.