Java_图片切片
package com.creditease.fetch.credit.util.similarity;import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;/*** 圖片切割工具類(lèi)*/
public class ImageCuter {/*** 切割圖片** @param image 源文件* @param width 切片寬度* @param height 切片高度* @param rowsLimit 縱向切片總數(shù)* @param colsLimit 橫向切片總數(shù)* @return* @throws Exception*/public static List<BufferedImage> cut(BufferedImage image, int width, int height, Integer rowsLimit, Integer colsLimit){List<BufferedImage> list = new ArrayList<>();int sWidth = image.getWidth(); // 圖片寬度int sHeight = image.getHeight(); // 圖片高度if (sWidth > width && sHeight > height) {int cols = 0; // 橫向切片總數(shù)int rows = 0; // 縱向切片總數(shù)int eWidth = 0; // 末端切片寬度int eHeight = 0; // 末端切片高度if (sWidth % width == 0) {cols = sWidth / width;} else {eWidth = sWidth % width;cols = sWidth / width + 1;}if (sHeight % height == 0) {rows = sHeight / height;} else {eHeight = sHeight % height;rows = sHeight / height + 1;}if (rowsLimit != null) {rows = rowsLimit;}if (colsLimit != null) {cols = colsLimit;}BufferedImage subImage = null;int cWidth = 0; // 當(dāng)前切片寬度int cHeight = 0; // 當(dāng)前切片高度for (int i = 0; i < rows; i++) {for (int j = 0; j < cols; j++) {cWidth = getWidth(j, cols, eWidth, width);cHeight = getHeight(i, rows, eHeight, height);// x坐標(biāo),y坐標(biāo),寬度,高度subImage = image.getSubimage(j * width, i * height, cWidth,cHeight);list.add(subImage);}}}return list;}/*** 獲取當(dāng)前切片的寬度** @param index 橫向索引* @param cols 橫向切片總數(shù)* @param endWidth 末端切片寬度* @param width 切片寬度* @return*/private static int getWidth(int index, int cols, int endWidth, int width) {if (index == cols - 1) {if (endWidth != 0) {return endWidth;}}return width;}/*** 獲取當(dāng)前切片的高度** @param index 縱向索引* @param rows 縱向切片總數(shù)* @param endHeight 末端切片高度* @param height 切片高度* @return*/private static int getHeight(int index, int rows, int endHeight, int height) {if (index == rows - 1) {if (endHeight != 0) {return endHeight;}}return height;}public static void main(String[] args) {
// ImageCuter imageCuter = new ImageCuter();
// try {
// imageCuter.cut(new File("t5.jpg"), "E:\\test2\\", 16, 16);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
}
}
?
轉(zhuǎn)載于:https://www.cnblogs.com/gisblogs/p/6823949.html
總結(jié)
- 上一篇: 团队作业5——测试与发布(Alpha版本
- 下一篇: 对 Java 集合的巧妙利用