我正在学习JavaSwing。我想在画面上画一幅图像,但我希望画出的画面分辨率为300 * 300。这是我在面板上绘制图像的代码。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Picture
{
JFrame frame;
public static void main(String[] args)
{
Picture poo = new Picture();
poo.go();
}
private void go()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
frame.getContentPane().add(new ImageOne());
}
class ImageOne extends JPanel
{
public void paintComponent(Graphics g)
{
Image img = new ImageIcon("image.jpg").getImage();
g.drawImage(img, 2, 2, this);
}
}
}
谁能告诉我怎么做?我在网上搜索,但我可以找到有关BufferedImage的解释,我不知道如何使用它。
提前致谢。
答案 0 :(得分:2)
我相信你正在寻找image.getScaledInstance(w,h,type)。这将图像缩放到给定宽度(w)和高度(h)到缩放类型。您想要使用的缩放类型是Image.SCALE_DEFAULT。由于getScaledInstace的工作方式,您必须创建一个新的BufferedImage。
所以你的代码看起来像这样
BufferedImage img = null;
try {
img = ImageIO.read(new FileInputStream(new File("image.jpg")));
} catch (Exception e) {}
//Scale image to 300x300
int width = 300;
int height = 300;
Image scaled = img.getScaledInstance(width, height, Image.SCALE_DEFAULT);
//Create new buffered image
BufferedImage tempBuff = new BufferedImage(width, height, img.getType());
// Create Graphics object
Graphics2D tempGraph = tempBuff.createGraphics();
// Draw the resizedImg from 0,0 with no ImageObserver then dispose
tempGraph.drawImage(scaled,0,0,null);
tempGraph.dispose();
g.drawImage((Image)tempBuff, 2, 2, this);