公司的APP要做一個九格切圖功能, 類似朋友圈那種一張大圖放上去.
本來已經用Python三十行搞定. 結果被測試部的質疑我不會用Java寫?? 一下子脾氣就上來了, 用Java寫了一個支持N格切圖的功能. 現在想想真是後悔, 浪費生命. 在此給大家貢獻出來
源碼已上傳至GitHub, 如果喜歡就點個星星啥的唄 https://github.com/HarrisonQi/GridCutter
思路:
- 讀取圖片
- 根據宮格數進行計算每個格子的X, Y座標
- 對每一個進行裁剪
1. 讀取圖片
讀取圖片的方式千千萬, 從本地或者從URL讀取皆可
- 通過URL讀取BufferedImage
// 需要對IOException進行處理, 一共兩處, 在URL連接處和文件讀取處
URL url = new URL("http://yihezo.cn/static/media/logo.9d4a5ade.png");
URLConnection connection = url.openConnection(); //打開連接
connection.setDoOutput(true);
connection.setReadTimeout(3000);// 設置超時時間(非必須)
BufferedImage img = ImageIO.read(connection.getInputStream());
- 通過本地文件路徑讀取BufferedImage
File file = new File("C:/a.png");
BufferedImage img = ImageIO.read(new FileInputStream(file));
2. 計算XY座標
我們拿四宮格爲例:
拿到一張圖片(假如它的寬和高都是300), 我們在腦海裏想象它切割後的樣子:
我們需要做的, 就是拿到A, B, C, D四個點的座標
很簡單的, 先讀取圖片的寬和高:
int height = img.getHeight();
int width = img.getWidth();
寬和高都拿到了, 接下來就很容易求出座標:(注意, 左上角爲0,0)
- A(0,0)
B(img.getWidth()/2,0)
C(0, img.getWidth()/2)
D(img.getWidth()/2,img.getWidth()/2)
根據公式得出:
- A(0,0)
B(150,0)
C(0, 150)
D(150,150)
會用到原生的裁剪方法:
img.getSubimage(x座標, y座標, x長度, y長度)
3. 對每一個進行裁剪
思路: 兩層for循環計算出每個的橫縱座標, 並把圖片根據得出的座標進行裁剪
不說廢話, 直接上代碼:
public List<BufferedImage> getGridPics(int xColumns, int yColumns, BufferedImage img, String outFolderPath) throws IOException {
List<BufferedImage> resImgs = new ArrayList<>();
int index = 1;
for (int i = 1; i <= yColumns; i++) {
int height = img.getHeight();
int posY = height / yColumns * i - height / yColumns;
int lenY = height / yColumns;
for (int j = 1; j <= xColumns; j++) {
int width = img.getWidth();
int posX = width / xColumns * j - width / xColumns;
int lenX = width / xColumns;
BufferedImage resImg = img.getSubimage(posX, posY, lenX, lenY);
if (outFolderPath != null) {
if (outFolderPath.trim().length() > 0) {
if (!outFolderPath.endsWith("/")) {
// 若路徑字符串不以'/'結尾, 則補上
outFolderPath += "/";
}
File f = new File(outFolderPath + index + ".png");
ImageIO.write(resImg, "png", f);
}
}
resImgs.add(resImg);
index++;
}
}
return resImgs;
}
想必看完思路後, 你一定可以自己寫出來了.
如果還是不明白… 去github上直接下載吧!
https://github.com/HarrisonQi/GridCutter
以上代碼定有疏漏及更優方案, 若發現問題, 歡迎在評論區討論!