java生成透明图片

package com.zbj.nj.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {

	/**
	 * @return
	 */
	@RequestMapping("/getImage")
	public void getImage(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		// 设置头信息
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");
		ServletOutputStream out = response.getOutputStream();
		// 创建透明的图片
		this.getTransparencyImage(out, request);
		try {
			out.flush();
		} finally {
			out.close();
		}

		//
	}

	/**
	 * 获取参数信息
	 * @param request
	 * @return map 《包含fontFamily、style、fontSize、color、style[斜体、粗细]、text[完整的文本信息]》
	 */
	public Map getParameter(HttpServletRequest request){
		// 获取创建图片的信息参数
		Map map = new HashMap();
		//这两条暂时为使用 暂时无法实现效果
		map.put("layout", request.getParameter("layout"));// 布局?
		map.put("align", request.getParameter("align"));// 对齐
		//有效数据
		map.put("fontFamily", request.getParameter("fontFamily"));// 字体 √
		map.put("fontSize", request.getParameter("fontSize"));// 字体大小√
		map.put("color", request.getParameter("color"));// 字体颜色 √
		map.put("text", request.getParameter("text"));// 文本信息 √
		
		//获得字体颜色 rgb参数
		int color = Integer.parseInt(request.getParameter("color"));
		String b = String.valueOf(color % 256);
        color /= 256;
        String g = String.valueOf(color % 256);
        color /= 256;
        String r = String.valueOf(color % 256);
		
		map.put("r", r);
		map.put("g", g);
		map.put("b", b);
		
		//设置字体样式
		String bold = request.getParameter("bold").trim();
		String italic = request.getParameter("italic").trim();
		String style = String.valueOf(Font.PLAIN);//默认字体
		if ("" != bold && "" != italic){
			style = String.valueOf(Font.BOLD | Font.ITALIC);// 粗体&&斜体 √
		}else if("" != bold){//粗体 √
			style = String.valueOf(Font.BOLD);
		}else if("" != italic){
			style = String.valueOf(Font.ITALIC);// 斜体 √
		}
		map.put("style", style);
		
		return map ;
	}
	
	/**
	 * 创建透明的图片
	 * 
	 * @param out
	 * @throws IOException
	 */
	public void getTransparencyImage(OutputStream out, HttpServletRequest request) throws IOException {
		//获取数据处理
		Map map = this.getParameter(request);
		String fontFamily = map.get("fontFamily");
		int fontSize = Integer.parseInt(map.get("fontSize"));
		String text = map.get("text");
		
		//初始化基本数据
		int width = 1, height = 1, ascent = 1, line = 1;
		
		//获得正确的text的width, height
		Map resultMap = this.getTextInfo( map, width, height);
		line = Integer.parseInt(resultMap.get("line").toString());
		width = Integer.parseInt(resultMap.get("width").toString());
		height = (int)Double.parseDouble(resultMap.get("height").toString());//每一行的高度
		ascent = Integer.parseInt(resultMap.get("ascent").toString());
		// 创建BufferedImage对象
		BufferedImage image = new BufferedImage(width, (height+ascent)*line, BufferedImage.TYPE_INT_ARGB);
		// 获取Graphics2D
		Graphics2D g2d = image.createGraphics();

		// ---------- 增加下面的代码使得背景透明 -----------------
		image = g2d.getDeviceConfiguration().createCompatibleImage(width, (height+ascent)*line);
		g2d.dispose();
		g2d = image.createGraphics();
		// ---------- 背景透明代码结束 -----------------

//抗锯齿 让图片看起来更清晰
		RenderingHints rh = g2d.getRenderingHints();
		rh.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2d.setRenderingHints(rh);
		// 画图 Start
		//获得字体颜色
		int r = Integer.parseInt(map.get("r")),
		g = Integer.parseInt(map.get("g")),
		b = Integer.parseInt(map.get("b")) ;
		int style = Integer.parseInt(map.get("style"));
		
		// 设置字体 名称、样式、磅值大小(同时使用斜体和粗体)
		Font font = new Font(fontFamily, style, fontSize);

		g2d.setFont(font);
		// 设置字体颜色
		g2d.setColor(new Color(r, g, b));
		StringTokenizer st = new StringTokenizer(text, "\r\n");
		int i = 0;
		while (st.hasMoreTokens()) {
			i++;
			// str 显示的文字, x 文字距离左边的间距, y 文字距离上面的间距 和字体一样
			g2d.drawString(st.nextToken(), 0, (height+ascent) * i);
		}

		// 画图 End
		// 释放对象
		g2d.dispose();
		// 输出文件
		ImageIO.write(image, "png", out);
		// 保存文件
		ImageIO.write(image, "PNG", new File("F:/temp.png"));
	}
	
	/**
	 * 获取Text对应的信息
	 * @param map 《包含fontFamily、style、fontSize、color、style[斜体、粗细]、text[完整的文本信息]》
	 * @param width 宽度 默认为1
	 * @param height 高度 默认为1
	 * @return
	 */
	public Map getTextInfo(Map map, int width, int height){
		
		int fontSize = Integer.parseInt(map.get("fontSize"));
		String fontFamily = map.get("fontFamily");
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2d = image.createGraphics();
		
		Font font = new Font(fontFamily, Integer.parseInt(map.get("style")), fontSize);
		FontMetrics mets = g2d.getFontMetrics(font);
		int ascent = mets.getLeading();//FontMetrics对象所描述的Font的标准行间距
		double heightInPixels = mets.getHeight();// 文字行高
		
		int line = 0;//text行数
		int textWidth = 0;//文本最宽的width
		int tempWidth =0 ;//临时存储当前行文本Width
		StringTokenizer st = new StringTokenizer(map.get("text"), "\r\n");
		while (st.hasMoreTokens()) {
			line++;
			String printText = st.nextToken();
			//判断字符宽度, 保存最宽的字符的宽度
			Rectangle2D rec = this.getRectangle2D(map, printText);
			tempWidth = (int)rec.getWidth(); 
			if(textWidth < tempWidth){
				textWidth = tempWidth;
			}
			// str 显示的文字, x 文字距离左边的间距, y 文字距离上面的间距 和字体一样
			g2d.drawString(printText, 0, fontSize * line);
		}
		// 释放对象
		g2d.dispose();
		
		Map resultMap = new HashMap();
		resultMap.put("width", textWidth);
		resultMap.put("height", heightInPixels);
		resultMap.put("ascent", ascent);
		resultMap.put("line", line);
		
		return resultMap ;
	}
	
	/**
	 * 获取 Rectangle2D 对象
	 * @param map 《包含fontFamily、style、fontSize、color、style[斜体、粗细]、text[完整的文本信息]》
	 * @param printText 文本信息
	 * @return new Rectangle2D();
	 */
	public Rectangle2D getRectangle2D(Map map, String printText){
		BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2d = image.createGraphics();
		
		Font font = new Font(map.get("fontFamily"), Integer.parseInt(map.get("style")), Integer.parseInt(map.get("fontSize")));
		FontMetrics mets = g2d.getFontMetrics(font);
		Rectangle2D bounds = mets.getStringBounds(printText, null);
		
		return bounds ;
	}
	
}

 

/**
	 * 返回一个字体列表的XML
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/getFontXml.do")
	public void getxml(HttpServletRequest request, HttpServletResponse response)throws Exception{
		//设置头信息
		response.setContentType("text/xml;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		Document documentXml = DocumentHelper.createDocument();
		Element rootElement = documentXml.addElement("date");
		
		Element element1 = rootElement.addElement("font");
		element1.addAttribute("id", "jmdgz");
		element1.addAttribute("name", "金梅淡古字");
		Element element2 = rootElement.addElement("font");
		element2.addAttribute("id", "mnjdy");
		element2.addAttribute("name", "迷你简黛玉体");
		Element element3 = rootElement.addElement("font");
		element3.addAttribute("id", "msyh");
		element3.addAttribute("name", "微软雅黑");
		Element element4 = rootElement.addElement("font");
		element4.addAttribute("id", "hkcdt");
		element4.addAttribute("name", "华康彩带体");
		Element element5 = rootElement.addElement("font");
		element5.addAttribute("id", "kt");
		element5.addAttribute("name", "楷体");
		Element element6 = rootElement.addElement("font");
		element6.addAttribute("id", "st");
		element6.addAttribute("name", "宋体");
		Element element7 = rootElement.addElement("font");
		element7.addAttribute("id", "ht");
		element7.addAttribute("name", "黑体");
		Element element8 = rootElement.addElement("font");
		element8.addAttribute("id", "arial");
		element8.addAttribute("name", "Arial");
		Element element9 = rootElement.addElement("font");
		element9.addAttribute("id", "timesnewroman");
		element9.addAttribute("name", "Times New Roman");
		Element element10 = rootElement.addElement("font");
		element10.addAttribute("id", "vrinda");
		element10.addAttribute("name", "Vrinda");
		

		//系统默认字体
//		GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
//		String[] styleArrays = ge.getAvailableFontFamilyNames();
//		for (int i = 0; i < styleArrays.length; i++) {
//			Element element = rootElement.addElement("font");
//			element.addAttribute("id", "zy");
//			element.addAttribute("name", styleArrays[i]);
//		}
		
		response.getWriter().print(documentXml.asXML());
		response.getWriter().close();
	}

 

 

jap代码:

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    My JSP 'index.jsp' starting page
	
	
	    
	
	
	
  
  
   
    This is my JSP page. 
<%=basePath%>

斜体italic

布局layout

对齐align

字体font-family

字体大小fontSize

颜色color

粗细bold

文本text

 

文中使用的.ttf文件, 自行下载!

或者,下载百度网盘的完整代码, 附带.ttf字体脚本

http://pan.baidu.com/s/1wyxIT

 

 

 

你可能感兴趣的:(java)