图像裁剪即截取原始图像某一部分生成一幅新的图像,某些app也会要求用户将上传图像进行一定程度裁剪来作为头像。图像裁剪实现起来比较简单,下面介绍两种裁剪方式,矩形裁剪和圆形裁剪。
矩形裁剪,定义图像上某个坐标(x,y)作为裁剪起始位置,xLength和yLength作为水平方向和垂直方向裁剪长度。由于裁剪范围可能超限,即裁剪起始位置到裁剪长度超过原始图像图像范围,需要判断(x+xLength)是否大于图像宽width。
圆形裁剪,定义图像上某个坐标(x,y)作为圆心,设定裁剪半径radius。判断横坐标是否超限,以radius是否大于圆心x和x+radius是否大于图像宽度作为条件,如果超限,再判断是圆心左侧还是右侧,最后以最小值对radius重新赋值。纵坐标以同样方式判断是否超限,并确定是否对radius重新赋值。
完整代码如下:
public class ImageCut {
/**
* 矩形裁剪,设定起始位置,裁剪宽度,裁剪长度
* 裁剪范围需小于等于图像范围
* @param image
* @param xCoordinate
* @param yCoordinate
* @param xLength
* @param yLength
* @return
*/
public BufferedImage imageCutByRectangle(BufferedImage image, int xCoordinate, int yCoordinate, int xLength,
int yLength) {
//判断x、y方向是否超过图像最大范围
if((xCoordinate + xLength) >= image.getWidth()) {
xLength = image.getWidth() - xCoordinate;
}
if ((yCoordinate + yLength) >= image.getHeight()) {
yLength = image.getHeight() - yCoordinate;
}
BufferedImage resultImage = new BufferedImage(xLength, yLength, image.getType());
for (int x = 0; x < xLength; x++) {
for (int y = 0; y < yLength; y++) {
int rgb = image.getRGB(x + xCoordinate, y + yCoordinate);
resultImage.setRGB(x, y, rgb);
}
}
return resultImage;
}
/**
* 圆形裁剪,定义圆心坐标,半径
* 裁剪半径可以输入任意大于零的正整数
* @param image
* @param xCoordinate
* @param yCoordinate
* @param radius
* @return
*/
public BufferedImage imageCutByCircle(BufferedImage image, int xCoordinate, int yCoordinate, int radius) {
//判断圆心左右半径是否超限
if ((xCoordinate + radius) > image.getWidth() || radius > xCoordinate) {
int a = image.getWidth() - 1 - xCoordinate;
if (a > xCoordinate) {
radius = xCoordinate;
}else {
radius = a;
}
}
//判断圆心上下半径是否超限
if ((yCoordinate + radius) > image.getHeight() || radius >yCoordinate) {
int a = image.getHeight() - 1 - yCoordinate;
if (a > yCoordinate) {
radius = yCoordinate;
}else {
radius = a;
}
}
int length = 2 * radius + 1;
BufferedImage resultImage = new BufferedImage(length, length, image.getType());
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
int x = i - radius;
int y = j - radius;
int distance = (int) Math.sqrt(x * x + y * y);
if (distance <= radius) {
int rgb = image.getRGB(x + xCoordinate, y + yCoordinate);
resultImage.setRGB(i, j, rgb);
}
}
}
return resultImage;
}
public static void main(String[] args) throws Exception {
File input = new File("C:/Users/admin/Desktop/1.jpg");
File output = new File("C:/Users/admin/Desktop/3.jpg");
BufferedImage image = ImageIO.read(input);
BufferedImage result = new ImageCut().imageCutByCircle(image, 80, 80, 80);
ImageIO.write(result, "jpg", output);
}
}
测试一下
原图:
矩形裁剪:
圆形裁剪: