javascript - <img>标签传参如何生成图片?
PHPz
PHPz 2017-04-11 11:29:03
[JavaScript讨论组]

PHPz
PHPz

学习是最好的投资!

全部回复(2)
黄舟

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

黄舟

题主的问题是如何传参,在 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中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号