1. 程式人生 > >Java 動態生成jpg圖片

Java 動態生成jpg圖片

1、生成一個頁面資料:

  
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;// 圖片的寬度  
  
        int imageHeight = 1000;// 圖片的高度  
  
        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("手機號      : " + policyPersonDto.getMobile(), 50, num);  
        num += 50;  
        graphics.drawString("登陸密碼    : " + policyPersonDto.getPassword(), 50, num);  
        num += 50;  
        graphics.drawString("身份證號    : " + policyPersonDto.getIdentityCard(), 50, num);  
        num += 50;  
        graphics.drawString("姓名        : " + policyPersonDto.getUserName(), 50, num);  
        num += 50;  
        graphics.drawString("所在地區    : " + policyPersonDto.getArea(), 50, num);  
        num += 50;  
        graphics.drawString("常住地址    : " + 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("商品編號    : " + policyProductDto.getProductId(), 50, num);  
        num += 50;  
        graphics.drawString("購買日期    : " + policyProductDto.getPurchaseDate(), 50, num);  
        num += 50;  
        graphics.drawString("購買價格    : " + policyProductDto.getPurchasePrice(), 50, num);  
        num += 50;  
        graphics.drawString("購買途徑    : " + policyProductDto.getPurchaseWay(), 50, num);  
        num += 50;  
        graphics.drawString("報修電話    : " + policyProductDto.getWarrantyPhone(), 50, num);  
        num += 50;  
        graphics.drawString("延保單位    : " + policyProductDto.getExtendedWarrantyUnit(), 50, num);  
        num += 50;  
        graphics.drawString("延保電話    : " + policyProductDto.getExtendedWarrantyPhone(), 50, num);  
        num += 50;  
        graphics.drawString("發票編號    : " + 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", "使用人資訊");  
        list.add(mapTitle1);  
          
        Map<String, String> map1 = new HashMap<String, String>();  
        map1.put("客戶姓名", "張三");  
        map1.put("手機號", "123123");  
        map1.put("身份證號", "230302198811241234");  
        list.add(map1);  
          
        Map<String, String> map2 = new HashMap<String, String>();  
        map2.put("送貨地址", "北京市海淀區知春路113號銀網中心B座1009室");  
        list.add(map2);  
          
        Map<String, String> map3 = new HashMap<String, String>();  
        map3.put("微訊號碼", "123123");  
        map3.put("qq號碼", "123123");  
        map3.put("電子郵箱", "
[email protected]
"); list.add(map3); Map<String, String> mapTitle2 = new HashMap<String, String>(); mapTitle2.put("title", "購買人資訊"); list.add(mapTitle2); Map<String, String> map4 = new HashMap<String, String>(); map4.put("姓名", "張三朋友"); map4.put("手機號", "15612341122"); map4.put("身份證號", "230302198811241234"); list.add(map4); Map<String, String> mapTitle3 = new HashMap<String, String>(); mapTitle3.put("title", "產品資訊"); list.add(mapTitle3); Map<String, String> map5 = new HashMap<String, String>(); map5.put("產品型號", "ALI88"); map5.put("憑證型別", "發票"); map5.put("購買日期", "2014-12-02"); list.add(map5); Map<String, String> map6 = new HashMap<String, String>(); map6.put("購買商城", "ALI88"); map6.put("憑證編號", "發票"); list.add(map6); int imageWidth = 1200;// 圖片的寬度 int imageHeight = 1000;// 圖片的高度 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("註冊保單", 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、生成一個表格:

public void graphicsGeneration() throws Exception {
		// 實際資料行數+標題+備註
		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));

		// 畫橫線
		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);
		}
		// 末行
		graphics.setColor(Color.black);
		graphics.drawLine(startWidth, imageHeight - 90, imageWidth - 5,
				imageHeight - 90);

		// 畫豎線
		for (int k = 0; k < totalcol; k++) {
			graphics.setColor(Color.black);
			graphics.drawLine(startWidth + k * colwidth, startHeight
					+ rowheight, startWidth + k * colwidth, imageHeight - 50);
		}
		// 末列
		graphics.setColor(Color.black);
		graphics.drawLine(imageWidth - 5, startHeight + rowheight,
				imageWidth - 5, imageHeight - 50);

		// 設定字型
		Font font = new Font("華文楷體", Font.BOLD, 20);
		graphics.setFont(font);

		// 寫標題
		String title = "標題寫在這裡";
		graphics.drawString(title, imageWidth / 3 + startWidth, startHeight
				+ rowheight - 10);

		font = new Font("華文楷體", Font.BOLD, 18);
		graphics.setFont(font);

		// 寫入表頭
		String[] headCells = { "編號", "名稱", "年齡", "性別", "體重" };
		for (int m = 0; m < headCells.length; m++) {
			graphics.drawString(headCells[m].toString(), startWidth + colwidth
					* m + 5, startHeight + rowheight * 2 - 10);
		}

		// 設定字型
		font = new Font("華文楷體", Font.PLAIN, 16);
		graphics.setFont(font);
		String[][] cellsValue = { { "101", "xiaozhang", "13", "M", "55" },
				{ "102", "xiaowang", "14", "F", "53" },
				{ "103", "同事接聽,工作資訊核實無誤,收入純打卡,無現金髮薪同事接聽,工作資訊核實無誤,收入純打卡,無現金髮薪同事接聽,工作資訊核實無誤,收入純打卡,無現金髮薪同事接聽,工作資訊核實無誤,收入純打卡,無現金髮薪", "15", "M", "58" } };
		// 寫入內容
		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("華文楷體", Font.BOLD, 18);
		graphics.setFont(font);
		graphics.setColor(Color.RED);

		// 寫備註
		String remark = "備註:備註寫在這裡。";
		graphics.drawString(remark, startWidth, imageHeight - 30);

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

		ImageIO.write(image, "jpg", new File("D:\\1.jpg"));
	}

3、實現條碼列印原始碼,Graphics2D 在圖片上畫表格,圖片等

/**
     * 列印模版
     *
     * @param imgWidth    圖片的寬度
     * @param imgHeight   圖片的高度
     * @param x           起始x軸
     * @param y           起始y軸
     * @param rowHeight   每行的高度
     * @param dataStart   資料縮排
     * @param firstWidth  第一列間距x座標
     * @param secondWidth 第二列間距x座標
     * @param thirdWidth  第三列間距x座標
     * @param fourWidth   第四列間距x座標
     * @param tb  實體物件
     * @return BufferedImage
     *(引數自己定,我的是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,
                                                Tb tb) {
        //空白麵板  也可是張圖片
        BufferedImage image = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = null;
 
        try {
 
            g = image.createGraphics();// 得到圖形上下文
            g.setBackground(Color.WHITE);//設定背景色
            g.fillRect(x, y, imgWidth, imgHeight);//填充整個螢幕
            g.setColor(Color.BLACK);//設定畫筆顏色
//            g.setFont(new Font("Arial", Font.LAYOUT_LEFT_TO_RIGHT, 12));// 設定字型   這種以及“非國產”是亂碼  有辦法解決的話也可為實線, 我認為亂碼是因為條碼印表機的緣故,這樣就要二次開發印表機,所以我沒要這種方法
            g.setFont(new Font("微軟雅黑", Font.TYPE1_FONT, 12));// 設定字型 還可設定為Font.ITALIC 就這兩種條碼印表機打印出來的的線是實體線
//            g.setFont(new Font("simsun", Font.TYPE1_FONT, 12));// jvm裡   想將字型格式simsun存入jvm裡直接呼叫,打印出來也不成
 
            g.drawLine(x, y, imgWidth, y);// 第一條橫線
 
            g.drawLine(x, y, x, rowHeight);//豎線
//            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("程式碼", dataStart, rowHeight * 2 - 5);    // * 2代表第二行
            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);
 
            //其他資料....
 
            //最後一條線
            g.drawLine(x, imgHeight - 1, imgWidth, imgHeight - 1);
 
            //在指定座標(198,61)處 寫入二維碼或其它圖片
            g.drawImage(ImageIO.read(getServletContext().getResourceAsStream(t.getPicUrl())), null, 198, 61);
            g.dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return image;
    }