AppOrH5端保存图片,Html转Image

废话不多说直接上代码
HttpServletRequest httpRequest=request;
String strUrl = "http://" + request.getServerName() //服务器地址
        + ":"
        + request.getServerPort()
        + httpRequest.getContextPath() //端口号
        + "/item/"+ productId+"-"+referrerIdTmp+"-000-000.html";
LOGGER.info("##########当前url地址###"+strUrl+"###############");

String text = strUrl; // 二维码内容
int width = 100; // 二维码图片宽度
int height = 100; // 二维码图片高度
String format = "jpg";// 二维码的图片格式

Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码

BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
        BarcodeFormat.QR_CODE, width, height, hints);
// 生成二维码
Properties upLoadProperties =  CommonSysUtil.getUpLoadProperties();
//二维码路径
String qrCodePath = upLoadProperties.getProperty("QRCODEIMAGEPATH")+"qrcodeImage"+productId+".jpg";
LOGGER.info("########图片二维码保存路径#####"+qrCodePath+"###############");

File outputFile = new File(qrCodePath);
//File outputFile = new File("d:" + File.separator + "new.jpg");
LOGGER.info("#################图片导入开始####################");
MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
LOGGER.info("#################图片导入结束####################");

UpyunConf upConf = sysHelperMapper.selectUpyunConf();
Map<String, String> muFile = uploadImgUpyun.uploadForABCSize(qrCodePath, upConf);
String oldImg = muFile.get("oldimg");


String htmlText = "<!DOCTYPE HTML>" +
        "<html>" +
        "<body>"+
        "<head>" +
        "<meta http-equiv='content-type' content='text/html' charset='gb2312'>" +
        "</head>" +
        "<div style='width:260px;'>"+
        "<table style='width: auto;margin: 0;border: 0 none;border-collapse: collapse;border-spacing: 0;background: transparent;'>"+
        "<tr>"+
        "<td style='white-space: nowrap;'>"+
        "<div style='width: 100%;height: 40px;font-weight: bold;font-size: 19px;color: rgb(51,51,51);text-align: center;line-height: 30px;padding: 5px 1px;'>二维码分享</div>"+
        "</td></tr><tr><td style='text-align: center;margin: 0 auto;'>"+
        "<div style='width: 100%;font-size: 14px;text-align: center;'>"+
        "<img style='width: 243px;height: auto;' src="+detailBean.getProductVo().getGoodsInfoImgId()+">"+
        "</div>"+
        "</td></tr>"+
        "<tr>"+
        "<td style='padding: 10px 0;'>"+
        "<table><tr><td>"+
        "<div style='color: rgb(51,51,51);'>"+
        "<div style='float: left;padding: 10px 10px 10px 20px;font-size: 16px;width: 160px;'>"+
        "<div style='font-weight: bold;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;'>"+
        detailBean.getProductVo().getProductName()+
        "</div>"+
        "<div style='color: rgb(255,168,0);margin-top: 24px;'>¥"+
        "<span style='font-size: 24px;'>"+
        detailBean.getProductVo().getGoodsInfoPreferPrice()+
        "</span>"+
        "</div>"+
        "</div>"+
        "</td><td>"+
        "<div style='float: right;font-size: 17px;text-align: center;width:100px;'>"+
        "<img style='width: 80px;height: 80px;' src="+oldImg+">"+
        "<div>长按保存</div>"+
        "</div>"+
        "</div>"+
        "</td></tr></table>"+
        "</td>"+
        "</tr>"+
        "</table>"+
        "</div>"+
        "<body>"+
        "</html>";

String saveImageLocation = upLoadProperties.getProperty("QRCODEIMAGEPATH")+"dialogImage"+productId+".jpg";
Html2ImageUtil.html2Img(htmlText,saveImageLocation);

LOGGER.info("########图片弹窗保存路径#####"+saveImageLocation+"###############");

Map<String, String> stringMap = uploadImgUpyun.uploadForABCSize(saveImageLocation, upConf);
/**
 *
 * @Description HTML转Image
 * @param htmText HTML文本字符串
 * @return 希望生成的Image Location
 */
public static String html2Img(String htmText, String saveImageLocation){

    HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
    try {
        imageGenerator.loadHtml(htmText);
        Thread.sleep(100);
        imageGenerator.getBufferedImage();
        Thread.sleep(200);
        imageGenerator.saveAsImage(saveImageLocation);
        //imageGenerator.saveAsHtmlWithMap("hello-world.html", saveImageLocation);
        //不需要转换位图的,下面三行可以不要
        BufferedImage sourceImg = ImageIO.read(new File(saveImageLocation));
        sourceImg = transform_Gray24BitMap(sourceImg);
        ImageIO.write(sourceImg, "BMP", new File(saveImageLocation));
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("将HTML文件转换成图片异常");
    }
    return saveImageLocation;
}
/**
 *
 * @Description 转换成24位图的BMP
 * @param image
 * @return
 */
public static BufferedImage transform_Gray24BitMap(BufferedImage image){

    int h = image.getHeight();
    int w = image.getWidth();
    int[] pixels = new int[w * h]; // 定义数组,用来存储图片的像素
    int gray;
    PixelGrabber pg = new PixelGrabber(image, 0, 0, w, h, pixels, 0, w);
    try {
        pg.grabPixels(); // 读取像素值
    } catch (InterruptedException e) {
        throw new RuntimeException("转换成24位图的BMP时,处理像素值异常");
    }

    for (int j = 0; j < h; j++){ // 扫描列
        for (int i = 0; i < w; i++) { // 扫描行
            // 由红,绿,蓝值得到灰度值
           /* gray = (int) (((pixels[w * j + i] >> 16) & 0xff) * 0.8);
            gray += (int) (((pixels[w * j + i] >> 8) & 0xff) * 0.1);
            gray += (int) (((pixels[w * j + i]) & 0xff) * 0.1);
            pixels[w * j + i] = (255 << 24) | (gray << 16) | (gray << 8) | gray;*/
        }
    }

    MemoryImageSource s= new MemoryImageSource(w,h,pixels,0,w);
    Image img =Toolkit.getDefaultToolkit().createImage(s);
    BufferedImage buf = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);//如果要转换成别的位图,改这个常量即可
    buf.createGraphics().drawImage(img, 0, 0, null);
    return buf;
}
/**
 * 返回大、中、小、原图
 *
 * @param muFile
 * @return Map集合,其中有4个值,oldimg是原图,0:小图、1:中图、2:大图
 */
public Map<String, String> uploadForABCSize(String muFile, UpyunConf upConf) {
    Map<String, String> imgMap = null;
    if (muFile != null) {
         // 获取上传文件的保存名称、服务器本地保存路径、后缀,拼接成文件地址
         UploadImgCommon.getPicNamePathSuffix();
        try {
            imgMap = new HashMap<String, String>();
            if (upConf != null) {
                YunBean yb = new YunBean();
                yb.setBucketName(upConf.getBucketName());
                yb.setPassword(upConf.getPassWord());
                yb.setUserName(upConf.getUserName());
                UpYunUtil.yunUp(muFile, UploadImgCommon.prefix, yb, UploadImgCommon.suffix);
                // 获取原图地址
                LOGGER.debug(LOGGERINFO1 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);
                imgMap.put(OLDIMG, upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);

                // 获取宽度集合,去除85这个宽度
                int[] widths = UploadImgCommon.getImgSetOut85(sysHelperMapper.selectImageSet());
                UploadImgCommon.sortWidth(widths);
                for (int i = 0; i < widths.length; i++) {
                    // 获取指定尺寸图片地址
                    LOGGER.debug(LOGGERINFO2 + widths[i] + LOGGERINFO3 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + widths[i]);
                    imgMap.put(i + "", upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + widths[i]);
                }

            }
        } catch (IllegalStateException e) {
            LOGGER.error(LOGGERINFO4, e);
        }  catch (Exception e) {
            LOGGER.error(LOGGERINFO4, e);
        }
    }

    return imgMap;
}

htmltoImage后台大致生成流程就是这样,具体细节可以自定义

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值