图片旋转则是将现有的图片,以中心位置为圆心,进行一定角度的旋转。
原图如下:
效果图如下:
核心代码如下:
@Component(value = "revolveFilter")
public class RevolvePictureFilter extends AbstractPictureFilter {
private double angle = 30;
/**
* log
**/
private static final Log log = LogFactory.getLog(RevolvePictureFilter.class);
/**
* 对像素color 进行处理
*
* @param color 原color
* @return 新color
*/
@Override
protected Color filterColor(Color color) {
return null;
}
/**
* 对图片增加滤镜
*
* @param image 图片
* @return 增加滤镜之后的图片
* 默认30度
*/
@Override
public BufferedImage pictureAddFilter(BufferedImage image) {
int srcWidth = image.getWidth();
int srcHeight = image.getHeight();
// calculate the new image size
Rectangle rectDes = calcRotatedSize(new Rectangle(new Dimension(
srcWidth, srcHeight)), angle);
BufferedImage res = null;
res = new BufferedImage(rectDes.width, rectDes.height,
BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2 = res.createGraphics();
// transform
g2.translate((rectDes.width - srcWidth) / 2,
(rectDes.height - srcHeight) / 2);
g2.rotate(Math.toRadians(angle), srcWidth / 2, srcHeight / 2);
g2.drawImage(image, null, null);
return res;
}
public static Rectangle calcRotatedSize(Rectangle src, double angel) {
// if angel is greater than 90 degree, we need to do some conversion
if (angel >= 90) {
if(angel / 90 % 2 == 1){
int temp = src.height;
src.height = src.width;
src.width = temp;
}
angel = angel % 90;
}
double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
double angelAlpha = (Math.PI - Math.toRadians(angel)) / 2;
double angelDaltaWidth = Math.atan((double) src.height / src.width);
double angelDaltaHeight = Math.atan((double) src.width / src.height);
int lenDaltaWidth = (int) (len * Math.cos(Math.PI - angelAlpha
- angelDaltaWidth));
lenDaltaWidth=lenDaltaWidth>0?lenDaltaWidth:-lenDaltaWidth;
int lenDaltaHeight = (int) (len * Math.cos(Math.PI - angelAlpha
- angelDaltaHeight));
lenDaltaHeight=lenDaltaHeight>0?lenDaltaHeight:-lenDaltaHeight;
int desWidth = src.width + lenDaltaWidth * 2;
int desHeight = src.height + lenDaltaHeight * 2;
desWidth=desWidth>0?desWidth:-desWidth;
desHeight=desHeight>0?desHeight:-desHeight;
return new java.awt.Rectangle(new Dimension(desWidth, desHeight));
}
}