Java dynamically generates jpg images

https://blog.csdn.net/hechurui/article/details/51995125


  
import java.awt.Color;  
import java.awt.Font;  
import java.awt.Graphics;  
import java.awt.image.BufferedImage;  
import java.io.BufferedOutputStream;  
import java.io.FileOutputStream;  
import java.util.ArrayList;  
import java.util.HashMap;  
import java.util.List;  
import java.util.Map;  
  
import com.haier.bean.PolicyBean;  
import com.haier.dto.PolicyPersonDto;  
import com.haier.dto.PolicyProductDto;  
import com.sun.image.codec.jpeg.JPEGCodec;  
import com.sun.image.codec.jpeg.JPEGImageEncoder;  
  
public class PictureUtil {  
  
    private static void createImage(String fileLocation, BufferedImage image) {  
        try {  
            FileOutputStream fos = new FileOutputStream(fileLocation);  
            BufferedOutputStream bos = new BufferedOutputStream(fos);  
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);  
            encoder.encode(image);  
            bos.close();  
            fos.close();  
        } catch (Exception e) {  
            e.printStackTrace ();  
        }  
    }  
  
    public static void graphicsGeneration(String path, PolicyBean policyBean) {  
  
        int imageWidth = 1000;//The width of the image  
  
        int imageHeight = 1000;//The height of the image  
  
        BufferedImage image = new BufferedImage(imageWidth, imageHeight,  
                BufferedImage.TYPE_INT_RGB);  
        Graphics graphics = image.getGraphics();  
        graphics.setColor(Color.white);  
        graphics.fillRect(0, 0, imageWidth, imageHeight);  
        graphics.setColor(Color.ORANGE);  
        graphics.setFont(new Font("宋体", Font.BOLD, 20));  
          
        PolicyPersonDto policyPersonDto = policyBean.getPolicyPersonDto();  
        PolicyProductDto policyProductDto = policyBean.getPolicyProductDto();  
          
        int num = 50;  
        graphics.drawString("Mobile number: " + policyPersonDto.getMobile(), 50, num);  
        num += 50;  
        graphics.drawString("Login password: " + policyPersonDto.getPassword(), 50, num);  
        num += 50;  
        graphics.drawString("ID ​​number: " + policyPersonDto.getIdentityCard(), 50, num);  
        num += 50;  
        graphics.drawString("姓名        : " + policyPersonDto.getUserName(), 50, num);  
        num += 50;  
        graphics.drawString("Area: " + policyPersonDto.getArea(), 50, num);  
        num += 50;  
        graphics.drawString("Residential address: " + policyPersonDto.getAddress(), 50, num);  
        num += 50;  
        graphics.drawString("微信号      : " + policyPersonDto.getWechatNo(), 50, num);  
        num += 50;  
        graphics.drawString("QQ号        : " + policyPersonDto.getQq(), 50, num);  
        num += 50;  
        graphics.drawString("Email       : " + policyPersonDto.getEmail(), 50, num);  
        num += 50;  
        graphics.drawString("品牌        : " + policyProductDto.getBrand(), 50, num);  
        num += 50;  
        graphics.drawString("型号        : " + policyProductDto.getModel(), 50, num);  
        num += 50;  
        graphics.drawString("Item ID: " + policyProductDto.getProductId(), 50, num);  
        num += 50;  
        graphics.drawString("Purchase Date: " + policyProductDto.getPurchaseDate(), 50, num);  
        num += 50;  
        graphics.drawString("Purchase price: " + policyProductDto.getPurchasePrice(), 50, num);  
        num += 50;  
        graphics.drawString("Purchase Way: " + policyProductDto.getPurchaseWay(), 50, num);  
        num += 50;  
        graphics.drawString("Repair phone: " + policyProductDto.getWarrantyPhone(), 50, num);  
        num += 50;  
        graphics.drawString("Extended Warranty Unit: " + policyProductDto.getExtendedWarrantyUnit(), 50, num);  
        num += 50;  
        graphics.drawString("Extended WarrantyPhone: " + policyProductDto.getExtendedWarrantyPhone(), 50, num);  
        num += 50;  
        graphics.drawString("Invoice number: " + policyProductDto.getInvoiceNo(), 50, num);  
  
        createImage(path, image);  
    }  
      
    public static void main(String[] args){  
        List<Map> list = new ArrayList<Map>();  
          
        Map<String, String> mapTitle1 = new HashMap<String, String>();  
        mapTitle1.put("title", "User Information");  
        list.add(mapTitle1);  
          
        Map<String, String> map1 = new HashMap<String, String>();  
        map1.put("Customer Name", "Zhang San");  
        map1.put("Mobile number", "123123");  
        map1.put("ID number", "230302198811241234");  
        list.add(map1);  
          
        Map<String, String> map2 = new HashMap<String, String>();  
        map2.put("Delivery Address", "Room 1009, Block B, Yinwang Center, No. 113 Zhichun Road, Haidian District, Beijing");  
        list.add(map2);  
          
        Map<String, String> map3 = new HashMap<String, String>();  
        map3.put("WeChat code", "123123");  
        map3.put("qq号码", "123123");  
        map3.put("E-mail", "[email protected]");  
        list.add(map3);  
  
        Map<String, String> mapTitle2 = new HashMap<String, String>();  
        mapTitle2.put("title", "Purchaser Information");  
        list.add(mapTitle2);  
          
        Map<String, String> map4 = new HashMap<String, String>();  
        map4.put("Name", "Zhang Sanyou");  
        map4.put("Mobile number", "15612341122");  
        map4.put("ID number", "230302198811241234");  
        list.add(map4);  
  
        Map<String, String> mapTitle3 = new HashMap<String, String>();  
        mapTitle3.put("title", "Product Information");  
        list.add(mapTitle3);  
  
        Map<String, String> map5 = new HashMap<String, String>();  
        map5.put("Product Model", "ALI88");  
        map5.put("Voucher Type", "Invoice");  
        map5.put("Purchase Date", "2014-12-02");  
        list.add(map5);  
  
        Map<String, String> map6 = new HashMap<String, String>();  
        map6.put("Purchase Mall", "ALI88");  
        map6.put("document number", "invoice");  
        list.add(map6);  
  
        int imageWidth = 1200;//The width of the image  
  
        int imageHeight = 1000;//The height of the image  
  
        BufferedImage image = new BufferedImage(imageWidth, imageHeight,  
                BufferedImage.TYPE_INT_RGB);  
        Graphics graphics = image.getGraphics();  
        graphics.setColor(Color.white);  
        graphics.fillRect(0, 0, imageWidth, imageHeight);  
        graphics.setColor(Color.black);  
  
        int high = 100;  
        int wigth = 0;  
        graphics.setFont(new Font("宋体", Font.BOLD, 50));  
        graphics.drawString("Register Policy", 500, high);  
        graphics.setFont(new Font("宋体", Font.BOLD, 20));  
        high += 10;  
        graphics.drawLine(50, high, 1150, high);  
          
        for(Map<String, String> rowMap : list){  
            high += 50;  
            wigth = 50;  
            for(Map.Entry<String, String> entry : rowMap.entrySet()){  
                String name = entry.getKey() + ":" + entry.getValue();  
                if("title".equals(entry.getKey())){  
                    high += 50;  
                    graphics.setFont(new Font("黑体", Font.BOLD, 30));  
                    graphics.drawString(entry.getValue(), wigth, high);  
                    graphics.setFont(new Font("宋体", Font.BOLD, 20));  
                } else {  
                    graphics.drawString(name, wigth, high);  
                    wigth += 400;  
                }  
                  
            }  
        }  
          
        createImage("D://test1.jpg", image);  
      
    }  
  
}  

2. Generate a table:

public void graphicsGeneration() throws Exception {
		// Actual data lines + title + remarks
		int totalrow = 6;
		int totalcol = 5;
		int imageWidth = 1024;
		int imageHeight = totalrow * 40 + 20;
		int rowheight = 40;
		int startHeight = 10;
		int startWidth = 10;
		int colwidth = ((imageWidth - 20) / totalcol);

		BufferedImage image = new BufferedImage(imageWidth, imageHeight,
				BufferedImage.TYPE_INT_RGB);
		Graphics graphics = image.getGraphics();

		graphics.setColor(Color.WHITE);
		graphics.fillRect(0, 0, imageWidth, imageHeight);
		graphics.setColor(new Color(220, 240, 240));

		// draw horizontal line
		for (int j = 0; j < totalrow - 1; j++) {
			graphics.setColor(Color.black);
			graphics.drawLine(startWidth, startHeight + (j + 1) * rowheight,
					imageWidth - 5, startHeight + (j + 1) * rowheight);
		}
		// End line
		graphics.setColor(Color.black);
		graphics.drawLine(startWidth, imageHeight - 90, imageWidth - 5,
				imageHeight - 90);

		// draw vertical line
		for (int k = 0; k < totalcol; k++) {
			graphics.setColor(Color.black);
			graphics.drawLine(startWidth + k * colwidth, startHeight
					+ rowheight, startWidth + k * colwidth, imageHeight - 50);
		}
		// last column
		graphics.setColor(Color.black);
		graphics.drawLine(imageWidth - 5, startHeight + rowheight,
				imageWidth - 5, imageHeight - 50);

		// set font
		Font font = new Font("Chinese Regular", Font.BOLD, 20);
		graphics.setFont(font);

		// write title
		String title = "The title is written here";
		graphics.drawString(title, imageWidth / 3 + startWidth, startHeight
				+ rowheight - 10);

		font = new Font("Chinese Regular", Font.BOLD, 18);
		graphics.setFont(font);

		// write header
		String[] headCells = { "Number", "Name", "Age", "Sex", "Weight" };
		for (int m = 0; m < headCells.length; m++) {
			graphics.drawString(headCells[m].toString(), startWidth + colwidth
					* m + 5, startHeight + rowheight * 2 - 10);
		}

		// set font
		font = new Font("Chinese Kai Style", Font.PLAIN, 16);
		graphics.setFont(font);
		String[][] cellsValue = { { "101", "xiaozhang", "13", "M", "55" },
				{ "102", "xiaowang", "14", "F", "53" },
				{ "103", "Colleagues answer, work information is verified correct, income is only punched, no cash pay colleagues answer, work information is verified correct, income is only punched, no cash pay colleagues answer, work information is verified correct, income is only punched, Colleagues answer the call without cash payment, the work information is verified and correct, the income is only punched in, and there is no cash payment", "15", "M", "58" } };
		// write content
		for (int n = 0; n < cellsValue.length; n++) {
			String[] arr = cellsValue[n];
			for (int l = 0; l < arr.length; l++) {
				graphics.drawString(cellsValue[n][l].toString(), startWidth
						+ colwidth * l + 5, startHeight + rowheight * (n + 3)
						- 10);
			}
		}

		font = new Font("Chinese Regular", Font.BOLD, 18);
		graphics.setFont(font);
		graphics.setColor(Color.RED);

		// write remarks
		String remark = "Remarks: Remarks are written here.";
		graphics.drawString(remark, startWidth, imageHeight - 30);

		//createImage("D:\\1.jpg");

		ImageIO.write(image, "jpg", new File("D:\\1.jpg"));
	}
3. Realize the source code of barcode printing, Graphics2D draws tables, pictures, etc. on the picture

/**
     * print template
     *
     * @param imgWidth The width of the image
     * @param imgHeight The height of the image
     * @param x starting x-axis
     * @param y start y axis
     * @param rowHeight The height of each row
     * @param dataStart data indent
     * @param firstWidth the first column spacing x coordinate
     * @param secondWidth second column spacing x coordinate
     * @param thirdWidth The third column spacing x coordinate
     * @param fourWidth the fourth column spacing x coordinate
     * @param tb entity object
     * @return BufferedImage
     *(The parameters are set by yourself, mine are 340, 200, 0, 0, 20, 10, 60, 190, 250, 340, tb)
     */
    private BufferedImage createTbGraphics(int imgWidth, int imgHeight, int x, int y, int rowHeight,
                                                int dataStart, int firstWidth, int secondWidth, int thirdWidth, int fourWidth,
                                                Tbtb) {
        //Blank panel can also be a picture
        BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = null;
 
        try {
 
            g = image.createGraphics();// Get the graphics context
            g.setBackground(Color.WHITE);//Set the background color
            g.fillRect(x, y, imgWidth, imgHeight);//fill the entire screen
            g.setColor(Color.BLACK);//Set the brush color
// g.setFont(new Font("Arial", Font.LAYOUT_LEFT_TO_RIGHT, 12));// Set the font and "non-domestic" is garbled, if there is a way to solve it, it can also be a solid line, I think the garbled code is because of the barcode Because of the printer, it is necessary to develop the printer twice, so I don't want this method
            g.setFont(new Font("Microsoft Yahei", Font.TYPE1_FONT, 12));// The font can also be set to Font.ITALIC The lines printed by these two barcode printers are solid lines
// g.setFont(new Font("simsun", Font.TYPE1_FONT, 12));// If you want to store the font format simsun in the jvm and call it directly, you can't print it out.
 
            g.drawLine(x, y, imgWidth, y);// The first horizontal line
 
            g.drawLine(x, y, x, rowHeight);//vertical line
//            g.drawString(new String("名称".getBytes("utf-8"),"utf-8"), dataStart, rowHeight - 5);
            g.drawString("名称", dataStart, rowHeight - 5);
            g.drawLine(firstWidth, y, firstWidth, rowHeight);
            g.drawString(tb.getName() == null ? "" :  tb.getName() , firstWidth + dataStart, rowHeight - 5);
            g.drawLine(imgWidth - 1, y, imgWidth - 1, rowHeight);
 
            g.drawLine(x, rowHeight, imgWidth, rowHeight); //横线
            g.drawLine(x, rowHeight, x, rowHeight * 2);
            g.drawString("code", dataStart, rowHeight * 2 - 5); // * 2 represents the second row
            g.drawLine(firstWidth, rowHeight, firstWidth, rowHeight * 2);
            g.drawString(tb.getCode() == null ? "" : tb.getCode()  , firstWidth + dataStart, rowHeight * 2 - 5);
            g.drawLine(secondWidth, rowHeight, secondWidth, rowHeight * 2);
 
            //other data....
 
            // last line
            g.drawLine(x, imgHeight - 1, imgWidth, imgHeight - 1);
 
            //Write a QR code or other image at the specified coordinates (198,61)
            g.drawImage(ImageIO.read(getServletContext().getResourceAsStream(t.getPicUrl())), null, 198, 61);
            g.dispose();
        } catch (IOException e) {
            e.printStackTrace ();
        }
 
        return image;
    }


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324822669&siteId=291194637