如何在不裁剪的情况下旋转缓冲图像?有没有办法旋转JLayeredPane或JLabel? [英] How to rotate a buffered image without cropping it? Is there any way to rotate a JLayeredPane or JLabel?

查看:218
本文介绍了如何在不裁剪的情况下旋转缓冲图像?有没有办法旋转JLayeredPane或JLabel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经搜过它,但我没有得到直截了当的回答。
我想要一个缓冲的图像被旋转但没有被裁剪
我知道新的尺寸会是这样的事情

  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)));

为我提供一种方法。



BTW有没有办法用 ImageIcon 旋转 JLabel



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



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

解决方案


如何旋转缓冲的图像而不对其进行裁剪?


通过计算旋转的 BufferedImage
另一半实际上是创建了旋转的 BufferedImage
您可以使用



旋转图像(30度)< br>


I had searched about it but I did not get straight forward answer. I want a buffered image to be rotated but not cropped I knew the new dimensions are gonna be some thing like this

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)));

Provide me a method for that.

BTW is there any way to rotate a JLabel with an ImageIcon?

Intention: adding to panels and layered pane and also saving it to file (saving the layered pane).

Or can we rotate the layered pane?

解决方案

How to rotate a buffered image without cropping it?

You had already half of the work by calculating the size of the rotated BufferedImage. The other half is actually creating the rotated BufferedImage. You can do that by using Graphics2D and applying some coordinate transformations before drawing the original image onto the new one. Furthermore, it makes sense to paint the "excess" area with some background color.

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;
}

Here is a test example from the above code:

Original image

Rotated image (by 30 degree)

这篇关于如何在不裁剪的情况下旋转缓冲图像?有没有办法旋转JLayeredPane或JLabel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆