java 將數據內容轉化為圖片


將數據內容轉化為圖片

public class WqcTestController {

public 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, List<Map> list) {		
	int imageWidth = 500;// 圖片的寬度
	int imageHeight = 500;// 圖片的高度
	
	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 = 30;    
    int wigth = 0;
    graphics.setFont(new Font("宋體", Font.BOLD, 30));           
    graphics.drawString("葯方詳情", 200, high);
    graphics.setFont(new Font("宋體", Font.BOLD, 20));    
    high += 10;    
    graphics.drawLine(0, high, 550, high);    
    
    for(Map<String, String> rowMap : list){    
        high += 50;    
        wigth = 40;    
        for(Map.Entry<String, String> entry : rowMap.entrySet()){    
            String name = entry.getKey() + ":" + entry.getValue();    
            if("title".equals(entry.getKey())){    
                high += 30;    
                graphics.setFont(new Font("黑體", Font.BOLD, 20));    
                graphics.drawString(entry.getValue(), wigth, high);    
                graphics.setFont(new Font("宋體", Font.BOLD, 20));    
            } else {    
                graphics.drawString(name, wigth, high);    
                wigth += 160;    
            }    

        }    
    }
    createImage(path,image);
    
}

/** 圖片名生成 **/
public static String genImageName() {
	//取當前時間的長整形值包含毫秒
	long millis = System.currentTimeMillis();
	//加上三位隨機數
	Random random = new Random();
	int end3 = random.nextInt(999);
	//如果不足三位前面補0
	String str = millis + String.format("%03d", end3);		
	return str;
}

public static void main(String[] args) {
	List<Map> list = new ArrayList<Map>();
	for (int i = 0; i < 8; i++) {			
		Map<String, String> mapTitle = new HashMap<String, String>();  
		mapTitle.put("單價/克", "20.0");
		mapTitle.put("克數", "1");
		mapTitle.put("名稱", "柴胡");
		list.add(mapTitle);
	}
	String path = "E:/upload/image";
	File newFileDir = new File(path);
	//如果不存在 則創建
    if (!newFileDir.exists()) {	            	
    	newFileDir.mkdirs();	           
    }
	graphicsGeneration(path+"/"+genImageName()+".jpg",list);
	System.out.println("完成");
	
}
  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM