您好我正在寻找一种方法来重新调整我的图像并仍然显示整个图像,所以它不会被切成两半或类似的东西。我也不允许使用任何类型的库。我用paintcomponent绘制图像。
有没有办法正确地做到这一点?
我已经尝试过这个了:
BufferedImage image = null;
try {
image = ImageIO.read(new File($question.getMediaFile().getPath())); /* Get the image */
Image scaled = image.getScaledInstance(350, 350, Image.SCALE_SMOOTH);
g.drawImage(scaled, w-350, 200, null);
} catch (IOException e) {
e.printStackTrace();
}
这会调整我的图像大小,但不显示整个图像,我想将其重新缩放为300 * 300或350 * 350大小的图像。
谢谢!
答案 0 :(得分:0)
使用getScaledInstance()
方法对我来说很好。这是我正在测试的代码:
public class Resize {
public static void main(String[] args) throws Exception {
final Image logo = ImageIO.read(new URL("http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png"));
final Dimension dim = new Dimension(logo.getWidth(null), logo.getHeight(null));
final JFrame frame = new JFrame();
frame.add(new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(logo.getScaledInstance(dim.width, dim.height, 0), 0, 0, this);
}
});
final JSlider xSlider = new JSlider(JSlider.HORIZONTAL, 1, dim.width*3, dim.width);
final JSlider ySlider = new JSlider(JSlider.VERTICAL, 1, dim.height*3, dim.height);
ChangeListener cl = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
dim.width = xSlider.getValue();
dim.height = ySlider.getValue();
frame.repaint();
}
};
xSlider.addChangeListener(cl);
ySlider.addChangeListener(cl);
frame.add(xSlider, "South");
frame.add(ySlider, "East");
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}