【问题标题】:How to rotate a buffered image without cropping it? Is there any way to rotate a JLayeredPane or JLabel?如何在不裁剪的情况下旋转缓冲图像?有没有办法旋转 JLayeredPane 或 JLabel?
【发布时间】:2017-10-20 13:03:09
【问题描述】:

我已经搜索过它,但我没有得到直接的答案。 我想要一个缓冲的图像被旋转但不被裁剪 我知道新维度会是这样的

int w = originalImage.getWidth();
int h = originalImage.getHeight();
double toRad = Math.toRadians(degree);
int hPrime = (int) (w * Math.abs(Math.sin(toRad)) + h * Math.abs(Math.cos(toRad)));
int wPrime = (int) (h * Math.abs(Math.sin(toRad)) + w * Math.abs(Math.cos(toRad)));

给我一​​个方法。

顺便说一句,有没有办法用ImageIcon 旋转JLabel

意图:添加到面板和分层窗格并将其保存到文件(保存分层窗格)。

或者我们可以旋转分层窗格吗?

【问题讨论】:

  • “如何在 java 中旋转缓冲图像而不裁剪它?有什么方法可以旋转 Jlayeredpane 或 Jlabel?” 当然,但如果图像填满整个宽度和高度,旋转图像的尺寸需要更大。这是简单的几何图形。
  • “意图:添加到面板和分层窗格并将其保存到文件中(保存分层窗格)。” 这确实解释不了为什么需要旋转图像.但是既然你提到它,我不建议尝试自己序列化组件。除非有更多细节,否则我倾向于将所有内容(包括旋转图像)写入更大的图像并序列化该更大的图像。

标签: java swing rotation bufferedimage jlayeredpane


【解决方案1】:

如何在不裁剪的情况下旋转缓冲图像?

通过计算旋转后的BufferedImage 的大小,您已经完成了一半的工作。 另一半实际上是创建旋转的BufferedImage。 您可以使用Graphics2D 来做到这一点 并在将原始图像绘制到新图像上之前应用一些坐标变换。此外,用一些背景颜色绘制“多余”区域是有意义的。

public BufferedImage rotateImage(BufferedImage originalImage, double degree) {
    int w = originalImage.getWidth();
    int h = originalImage.getHeight();
    double toRad = Math.toRadians(degree);
    int hPrime = (int) (w * Math.abs(Math.sin(toRad)) + h * Math.abs(Math.cos(toRad)));
    int wPrime = (int) (h * Math.abs(Math.sin(toRad)) + w * Math.abs(Math.cos(toRad)));

    BufferedImage rotatedImage = new BufferedImage(wPrime, hPrime, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = rotatedImage.createGraphics();
    g.setColor(Color.LIGHT_GRAY);
    g.fillRect(0, 0, wPrime, hPrime);  // fill entire area
    g.translate(wPrime/2, hPrime/2);
    g.rotate(toRad);
    g.translate(-w/2, -h/2);
    g.drawImage(originalImage, 0, 0, null);
    g.dispose();  // release used resources before g is garbage-collected
    return rotatedImage;
}

这是上面代码中的一个测试示例:

原图

旋转图像(30 度)

【讨论】:

    【解决方案2】:

    顺便说一句,有没有办法用 ImageIcon 旋转 JLabel?

    更简单的方法是旋转图标,而不是标签。

    查看Rotated Icon 的类,该类执行旋转并在图标旋转时重新计算图标的大小。

    意图:添加到面板和分层窗格并将其保存到文件(保存分层窗格)。

    不知道具体是什么意思,但如果您只想保存分层窗格的“图像”,请查看Screen Image

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 2015-02-18
      相关资源
      最近更新 更多