1. 程式人生 > 實用技巧 >【圖片分割器】Java完成圖片分隔

【圖片分割器】Java完成圖片分隔

刷朋友圈,看到很多人發分隔後的9宮格,出現一個大圖挺好看,所以自己用java寫了一個圖片分隔器。

可以自定義分隔數。

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @Description 圖片分隔-發微信朋友圈
 * @Author cheng2839
 * @Date 2018年10月04日
 * @Version v1.0
 */
public class MyTest028 {

    private static final String IMAGE_FILE_PATH 
= "E:\\timg.jpg"; //橫向分隔個數 private static final int SEP_X_NUM = 3; //縱向分隔個數 private static final int SEP_Y_NUM = 3; public static void main(String[] args) { try { sepImage(); } catch (IOException e) { e.printStackTrace(); } }
public static void sepImage() throws IOException { File file = new File(IMAGE_FILE_PATH); if (!file.exists() || !file.isFile()) { throw new RuntimeException("file not exists or un-file:" + IMAGE_FILE_PATH); } BufferedImage image = ImageIO.read(file);
int totalWidth = image.getWidth(); int totalHeight = image.getHeight(); int width = totalWidth / (SEP_X_NUM <=0?1:SEP_X_NUM); int height = totalHeight / (SEP_Y_NUM <=0?1:SEP_Y_NUM); File dirFile = new File(file.getParent(), file.getName().substring(0, file.getName().lastIndexOf("."))); if (!dirFile.exists()) { dirFile.mkdir(); } for (int y = 0, j = 1; y <= totalHeight-height; y+=height, j++) { for (int x = 0, i = 1; x <= totalWidth-width; x+=width, i++) { File targetFile = new File(dirFile, j+"_"+i+".jpg"); BufferedImage targetImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = targetImage.getGraphics(); System.out.println(targetFile.getPath() + ": x="+x+",y="+y+"; width="+width+", height="+height+"; totalWidth"+totalWidth+",totalHeight="+totalHeight); g.drawImage(image.getSubimage(x, y, width, height), 0, 0, null); ImageIO.write(targetImage, "JPG", targetFile); } } } }