gpt4 book ai didi

java - 如何调整图像大小和旋转图像

转载 作者:行者123 更新时间:2023-12-02 08:24:37 24 4
gpt4 key购买 nike

我想旋转图像,在下一个级别我想调整它的大小,请帮我。我创建一个从 JPanel 扩展的类并重写 PaintComponent() 方法用于绘制图像。

public class NewJPanel extends javax.swing.JPanel {

/** Creates new form NewJPanel */
public NewJPanel() {
initComponents();
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 20, 20, this);
}

最佳答案

这是我使用的一些代码。您可以修改它以满足您的需要。

调整图像大小:

/**
* Resizes the image
*
* @param filePath File path to the image to resize
* @param w Width of the image
* @param h Height of the image
* @return A resized image
*/
public ImageIcon resizeImage(String filePath, int w, int h) {
String data = filePath;
BufferedImage bsrc, bdest;
ImageIcon theIcon;
//scale the image
try {
if (dataSource == DataTypeEnum.file) {
bsrc = ImageIO.read(new File(data));
} else {
bsrc = ImageIO.read(new URL(filePath));
}
bdest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bdest.createGraphics();
AffineTransform at = AffineTransform.getScaleInstance(
(double) w / bsrc.getWidth(), (double) h / bsrc.getHeight());
g.drawRenderedImage(bsrc, at);
//add the scaled image
theIcon = new ImageIcon(bdest);
return theIcon;
} catch (Exception e) {
Window.getLogger().warning("This image can not be resized. " +
"Please check the path and type of file.");
//restore the old background
return null;
}
}

旋转图像:
注意:角度以弧度为单位

public static BufferedImage rotate(BufferedImage image, double angle) {
double sin = Math.abs(Math.sin(angle)),
cos = Math.abs(Math.cos(angle));
int w = image.getWidth(),
h = image.getHeight();
int neww = (int) Math.floor(w * cos + h * sin),
newh = (int) Math.floor(h * cos + w * sin);
GraphicsConfiguration gc = getDefaultConfiguration();
BufferedImage result =
gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
Graphics2D g = result.createGraphics();
g.translate((neww - w) / 2, (newh - h) / 2);
g.rotate(angle, w / 2, h / 2);
g.drawRenderedImage(image, null);
g.dispose();
return result;
}

关于java - 如何调整图像大小和旋转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4787066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com