java透明背景

原创
2016/10/13 21:56
阅读数 551
package top.lileix.test;

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;

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

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class App {
	@RequestMapping("/")
	@ResponseBody
	void home(HttpServletResponse response, String s) {

		int width = 55;
		int height = 55;
		int fontHeight = 55 / s.length()-3;
		String drawStr = s;
		BufferedImage buffImg = new BufferedImage(55, 55, BufferedImage.TYPE_INT_RGB);

		Graphics2D gd = buffImg.createGraphics();
		// 设置透明 start
		buffImg = gd.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
		gd = buffImg.createGraphics();
		// 设置透明 end

		// 画圆
		gd.setColor(Color.GRAY); // 设置颜色
		gd.fillOval(0, 0, 54, 54);

		gd.setFont(new Font("微软雅黑", Font.PLAIN, fontHeight)); // 设置字体
		gd.setColor(Color.white); // 设置颜色
		gd.drawString(drawStr, width / 2 - fontHeight * drawStr.length() / 2, (fontHeight + height) / 2-2); // 输出文字(中文横向居中)

		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		ServletOutputStream sos = null;
		try {
			sos = response.getOutputStream();
			ImageIO.write(buffImg, "png", sos);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (sos != null) {
				try {
					sos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) throws Exception {
		SpringApplication.run(App.class, args);
	}
}

springboot

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
2 收藏
1
分享
返回顶部
顶部