用Image中的getScaledInstance
方法得到一个按照指定宽度和高度缩放以后的Image实例,然后再用setImage方法设置ImageIcon所显示的图像\x0d\x0a一下示例:\x0d\x0aimportjavax.swing.*\x0d\x0aimportjava.awt.*\x0d\x0a\x0d\x0apublicclasstestextendsJFrame\x0d\x0a{\x0d\x0aprivateImageIconimg\x0d\x0aprivateJLabelshowImg\x0d\x0a\x0d\x0aprivatefinalstaticintWIDTH=147\x0d\x0aprivatefinalstaticintHEIGHT=136\x0d\x0a\x0d\x0apublictest()\x0d\x0a{\x0d\x0aimg=newImageIcon("1.png")\x0d\x0aimg.setImage(img.getImage().getScaledInstance(test.WIDTH,test.HEIGHT,Image.SCALE_DEFAULT))\x0d\x0a\x0d\x0ashowImg=newJLabel()\x0d\x0ashowImg.setIcon(img)\x0d\x0a\x0d\x0athis.add(showImg,BorderLayout.CENTER)\x0d\x0athis.setBounds(300,200,400,300)\x0d\x0athis.pack()\x0d\x0athis.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\x0d\x0athis.setVisible(true)\x0d\x0a}\x0d\x0a\x0d\x0apublicstaticvoidmain(Stringargs[])\x0d\x0a{\x0d\x0anewtest()\x0d\x0a}\x0d\x0a}
截取点代码片断,你自己看着改
修改图片大小用getScaledInstance方法
BufferedImage bimg = null
Image img = null
int width, height
try {
bimg = ImageIO.read(u)
if(bimg.getWidth() > bimg.getHeight())
{
width = 40
height = bimg.getHeight() * width / bimg.getWidth()
}
else
{
height = 40
width = bimg.getWidth() * height / bimg.getHeight()
}
img = bimg.getScaledInstance(width, height, Image.SCALE_DEFAULT)
pre_image = bimg.getScaledInstance(width * 10, height * 10, Image.SCALE_DEFAULT)
} catch (IOException e) {
e.printStackTrace()
}
评论列表(0条)