首页 > <img>标签传参如何生成图片?

<img>标签传参如何生成图片?

<img src="/GetText.aspx?Text=Post%3A%20200000%20%20E-mail%3A%20mp%40mingpian.sh&FontName=%E6%96%B9%E6%AD%A3%E9%AD%8F%E7%A2%91%E7%AE%80%E4%BD%93&FontSize=11&RGBColor=rgb(223%2C%2053%2C%20142)&Fontweight=Normal&Fontstyle=Normal"/>


题主的问题是如何传参,在 JSP 中,一般是通过 el 表达式来完成的。

<img src="/getText?text=${text.text}&amp;font_name=${text.font_name}&amp;font_size=${text.font_size}&amp;rgb_color=${text.rgb_color}&amp;font_weight=${text.font_weight}&amp;font_style=${text.font_style}">

至于 Java 后端的实现可以是这样的 (这里我以 SpringMVC 为例):

@RequestMapping(value = "getText",method = RequestMethod.GET)
public void getText(
            @RequestParam(value = "text",required = false,defaultValue = "这里输入文字")String text,
            @RequestParam(value = "font_name",required = false,defaultValue = "黑体")String font_name,
            @RequestParam(value = "rgb_color",required = false,defaultValue = "rgb(0,0,0)")String rgb_color,
            @RequestParam(value = "font_style",required = false,defaultValue = "0")String font_style,
            @RequestParam(value = "font_size",required = false,defaultValue = "14")String font_size,
            @RequestParam(value = "font_weight",required = false,defaultValue = "0")String font_weight,
            HttpServletResponse response) throws IOException {

        Graphics tmp = new BufferedImage(300,200,BufferedImage.TYPE_INT_ARGB).getGraphics();
        tmp.setFont(DrawUtil.getFont(font_name, Integer.parseInt(font_size), Integer.parseInt(font_style), Integer.parseInt(font_weight)));
        FontMetrics fm = tmp.getFontMetrics();
        tmp.dispose();

        BufferedImage image = new BufferedImage(fm.stringWidth(text),fm.getHeight(),BufferedImage.TYPE_INT_ARGB);
        Graphics g = image.getGraphics();
        ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setColor(DrawUtil.getColor(rgb_color));
        g.setFont(DrawUtil.getFont(font_name, Integer.parseInt(font_size), Integer.parseInt(font_style), Integer.parseInt(font_weight)));
        g.drawString(text, 0, fm.getHeight()-5);
        g.dispose();
        
        try(ByteArrayOutputStream os = new ByteArrayOutputStream(); 
            OutputStream osm = response.getOutputStream()){
            ImageIO.write(image, "png", os);
            response.setContentType("image/png");
            response.setCharacterEncoding("UTF-8");
            IOUtils.write(os.toByteArray(), osm);
            osm.flush();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

想要什么样的文字图片,由前端的 JSP 页面传递对应的参数即可。


php的话,后端使用gd库,c#的话,后端用gdi+都可以动态生成图片的

【热门文章】
【热门文章】