刷朋友圈,看到很多人发分隔后的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); } } } }