原创

java占位图生成工具类

作者:cndz 围观群众:703 更新于 标签:工具类占位图工具类占位图图片生成工具类

简介

生成指定大小文字颜色的图片。

效果

默认图片
指定文字

代码

    public static void genImageIo(String text, String title, int height, int width, Font font, Color bgColor, Color fontColor, HttpServletResponse response) throws IOException {
        //画布
        BufferedImage canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) canvas.getGraphics();
        g.setBackground(bgColor);//设置背景色
        g.clearRect(0, 0, width, height);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        String[] rows = makeLineFeed(text, metrics, width).split("\n");
        double lineSub = ((double) rows.length / 2);
        int y = (int) ((height / 2) - (font.getSize() * (lineSub - 0.75)));

        if ((y > font.getSize() + 30) && StringUtils.isNotBlank(title)) {
            Font titleFont = new Font("宋体", Font.BOLD, font.getSize() + 10);
            FontDesignMetrics tmetrics = FontDesignMetrics.getMetrics(titleFont);
            g.setColor(fontColor);
            g.setFont(titleFont);
            g.drawString(title, (width / 2) - (getLineLength(title, tmetrics) / 2), titleFont.getSize() + 30);
        }
        g.setColor(fontColor);
        g.setFont(font);
        if (rows.length == 1) {
            int x = (width / 2) - (getLineLength(rows[0], metrics) / 2);
            g.drawString(rows[0], x, y);
        } else {
            for (int i = 0; i < rows.length; i++) {
                if (i > 0) {
                    y += font.getSize() + 5;
                }
                g.drawString(rows[i], 20, y);
            }
        }
        byte[] captchaChallengeAsJpeg = null;

        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        ImageIO.write(canvas, "jpg", jpegOutputStream);
        //定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
加入收藏