總看别人微網誌的九宮格廣告,想想,實作倒是很簡單,應該說簡單到爆了,不過還是手寫實作一下吧
主要思想:
1. 一個待繪制的BufferedImage,長寬都是原圖的1/3
2. 使用graphics,通過偏移量選擇繪制原圖的區域
3. 繪制結束就可以輸出到檔案
4. 通過兩層循環,繪制9個位置的全部圖檔
說完上圖
原圖
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiIXZ05WZD9CX5RXa2Fmcn9CXwczLcVmds92czlGZvwVP9EUTDZ0aRJkSwk0LcxGbpZ2LcBDM08CXlpXazRnbvZ2LcRlMMVDT2EWNvwFdu9mZvwVP9cXW6JERNd3YtJGbCNjW1lzRaZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39zNxEjM1YTN0EjNyITM0EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
切分後的圖檔
代碼也比較簡單,實作起來很!方!便!
File imgfile;
Image originimg;
BufferedImage image;
Graphics g;
FileOutputStream out;
JPEGImageEncoder encoder;
try {
// 擷取原始圖檔
imgfile = new File("input.jpg");
originimg = ImageIO.read(imgfile);
// 擷取原始圖檔的寬和高
int width = originimg.getWidth(null);
int height = originimg.getHeight(null);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
// 九宮格,每張圖檔大小都為原來的1/3
image = new BufferedImage(width / 3, height / 3,
BufferedImage.TYPE_INT_RGB);
// 建立圖檔
g = image.createGraphics();
// 繪制圖檔
g.drawImage(originimg, width * -i / 3, height * -j / 3,
width, height, null);
// 圖檔繪制完成,關閉g
g.dispose();
// 輸出流和輸出檔案
out = new FileOutputStream("output" + i + "-" + j + ".jpg");
// 下面代碼将輸出圖檔轉換為JPEG、JPG檔案
encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
System.out.println("輸出檔案output" + i + "-" + j + ".jpg");
}
}
} catch (Exception e) {
e.printStackTrace();
}
打完收工
這裡的問題就在于長方形的圖檔切出來也是長方形的,未必好看,但是直接切成正方形的需要考慮截取哪一部分
以下圖為例
原圖為長方形的截圖效果如下
如果依然希望輸出正方型,壓縮圖檔效果不好,是以采用直接截取圖檔的方式
File imgfile;
Image originimg;
BufferedImage image;
Graphics g;
FileOutputStream out;
JPEGImageEncoder encoder;
try {
// 擷取原始圖檔
imgfile = new File("input3.jpg");
originimg = ImageIO.read(imgfile);
// 擷取原始圖檔的寬和高
int width = originimg.getWidth(null);
int height = originimg.getHeight(null);
// 如果輸入為長方形,重新計算長寬
int outputwidth = width > height ? height : width;
int outputheight = outputwidth;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
// 九宮格,每張圖檔大小都為原來的1/3
// 長方形,建立圖檔大小為計算後的正方型的1/3
image = new BufferedImage(outputwidth / 3,
outputheight / 3, BufferedImage.TYPE_INT_RGB);
// 建立圖檔
g = image.createGraphics();
// 繪制圖檔
// 長方形,計算偏移量的資料采用計算後的正方形
g.drawImage(originimg, outputwidth * -i / 3, outputheight
* -j / 3, width, height, null);
// 圖檔繪制完成,關閉g
g.dispose();
// 輸出流和輸出檔案
out = new FileOutputStream("output" + i + "-" + j + ".jpg");
// 下面代碼将輸出圖檔轉換為JPEG、JPG檔案
encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
System.out.println("輸出檔案output" + i + "-" + j + ".jpg");
}
}
} catch (Exception e) {
e.printStackTrace();
}
最終截取了正方形的部分,效果如下