某些证件照APP当你上传一张图片后,会自动帮你排版成多张图片。下方代码可以实现这种有间隔的自动排版功能。
运行结果:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Demo {
public static void main(String[] args) throws IOException {
int pageWidth = 105; //A6尺寸
int pageHeight = 148; //A6尺寸
int photoWidth = 25; //A1尺寸
int photoHeight = 35; //A1尺寸
int interval = 2; //间隙大小
File inFIle = new File("d:/AAfile/yh.jpg");
File outFIle = new File("d:/AAfile/yhheads.jpg");
draw(pageWidth,pageHeight,photoWidth,photoHeight,interval,inFIle,outFIle);
}
public static void draw(int pageWidth, int pageHeight, int photoWidth, int photoHeight,
int interval, File inFile, File outFile) throws IOException {
//这里pageWidth为什么是减去interval
int xNum = (pageWidth - interval) / (photoWidth + interval); //横向放置个数
int yNum = (pageHeight - interval) / (photoHeight + interval);//纵向放置个数
int left = (pageWidth + interval - (photoWidth + interval) * xNum) / 2;//横向起始点
int top = (pageHeight + interval - (photoHeight + interval) * yNum) / 2;//纵向起始点
int xpixel = getPixel(pageWidth);
int ypixel = getPixel(pageHeight);
BufferedImage photo = ImageIO.read(inFile);
BufferedImage bi = new BufferedImage(xpixel,ypixel,BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
//填充背景
g.setColor(Color.white);
g.fillRect(0,0,xpixel,ypixel);
//绘制图片
int xg,yg;
for (int i = 0; i < yNum; i++){
yg = getPixel(top + i * (photoHeight + interval));
for (int j = 0; j < xNum; j++){
xg = getPixel(left + j * (photoWidth + interval));
g.drawImage(photo,xg,yg,getPixel(photoWidth),getPixel(photoHeight),null);
}
}
//绘制辅助线 可设置无需辅助线
g.setColor(Color.black);
int x,y;
//纵向
for (int i = 0; i < xNum; i++){
xg = getPixel(left + i * (photoWidth + interval));
g.drawLine(xg,0,xg,ypixel);
x = xg + getPixel(photoWidth);
g.drawLine(x,0,x,ypixel);
}
//横向
for (int j = 0; j < yNum; j++){
yg = getPixel( top + j * (photoHeight + interval));
g.drawLine(0,yg,xpixel,yg);
y = yg + getPixel(photoHeight);
g.drawLine(0,y,xpixel,y);
}
g.dispose();
ImageIO.write(bi,"jpg",outFile);
}
/**
* 计算像素数
* 1毫米像素数=DPI/25.4
* DPI可更改 暂设300
*/
public static int getPixel(int mm){
return (int) (300/25.4)*mm;
}
}
其中需要花时间理解的就是计算能排几张照片,以及绘图、绘线功能。
为了使照片和白色背景边缘距离>=2mm,pageWidth需要先减去interval。
int xNum = (pageWidth - interval) / (photoWidth + interval); //横向放置个数
int yNum = (pageHeight - interval) / (photoHeight + interval);//纵向放置个数