【问题标题】:How to save rotated buffered image in another buffered image?如何将旋转的缓冲图像保存在另一个缓冲图像中?
【发布时间】:2016-04-04 06:18:19
【问题描述】:

我正在尝试使用getImage() 方法旋转缓冲的Image 并返回缓冲的Image(旋转图像)。正在发生图像旋转,但在保存时将图像按原样保存而不旋转图像。

初始化:

private BufferedImage transparentImage;

油漆组件:

AffineTransform at = new AffineTransform();
at.rotate(Math.toRadians(RotationOfImage.value));
Graphics2D g2d = (Graphics2D) g;

g2d.drawImage(transparentImage, at, null);
repaint();

一种返回旋转缓冲图像的方法。

 public BufferedImage getImage(){
     return transparentImage;
 }

【问题讨论】:

  • 为什么要在paintComponent 中旋转它?您应该绘制旋转后的图像。这样做不会对图像产生任何影响,因为您正在旋转组件的 Graphics 上下文

标签: java swing graphics


【解决方案1】:

基本上,您正在旋转组件的Graphics 上下文并将图像绘制到它,这对原始图像没有影响。

相反,您应该旋转图像并对其进行绘画,例如...

public BufferedImage rotateImage() {
    double rads = Math.toRadians(RotationOfImage.value);
    double sin = Math.abs(Math.sin(rads));
    double cos = Math.abs(Math.cos(rads));

    int w = transparentImage.getWidth();
    int h = transparentImage.getHeight();
    int newWidth = (int) Math.floor(w * cos + h * sin);
    int newHeight = (int) Math.floor(h * cos + w * sin);

    BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = rotated.createGraphics();
    AffineTransform at = new AffineTransform();
    at.translate((newWidth - w) / 2, (newHeight - h) / 2);

    at.rotate(Math.toRadians(RotationOfImage.value), w / 2, h / 2);
    g2d.setTransform(at);
    g2d.drawImage(transparentImage, 0, 0, this);
    g2d.setColor(Color.RED);
    g2d.drawRect(0, 0, newWidth - 1, newHeight - 1);
    g2d.dispose();
}

然后你可以画它像......

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    BufferedImage rotated = rotateImage();
    int x = (getWidth() - rotated.getWidth()) / 2;
    int y = (getHeight() - rotated.getHeight()) / 2;
    g2d.drawImage(rotated, x, y, this);
    g2d.dispose();
}

现在,您可以对此进行优化,因此您只在角度发生变化时生成图像的旋转版本,但我会留给您处理

ps-我没有测试过这个,但它是基于这个question

【讨论】:

  • "ps-我没有测试过这个.." Pfft..你这样做了多少次?我敢肯定我记得在这个网站上看过至少 3 次(而且我的记忆力很差)。
  • @AndrewThompson 由于我从库代码中复制了算法,希望它可以工作:P
  • 嗯.. BNI ... ;-)
  • 哦,如果代码中存在一些仅在罕见的极端情况下出现的故障,还有什么更好的媒介(比 SO)来发现并修复它?
猜你喜欢
  • 1970-01-01
  • 2013-02-25
  • 2016-10-12
  • 1970-01-01
  • 2020-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多