Algunas aplicaciones de fotos de identificación le darán formato automáticamente a varias imágenes después de que cargue una imagen. El siguiente código puede realizar esta función de composición tipográfica automática con intervalos.
resultado de la operación:
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;
}
}
Entre ellos, se necesita tiempo para comprender el cálculo de cuántas fotos se pueden organizar, así como las funciones de dibujar y dibujar líneas.
Para que la distancia entre la foto y el borde del fondo blanco sea >= 2 mm, primero se debe restar el ancho de página del intervalo.
int xNum = (pageWidth - interval) / (photoWidth + interval); //横向放置个数
int yNum = (pageHeight - interval) / (photoHeight + interval);//纵向放置个数