当前位置: 首页 > article >正文

Java 使用html2image将html生成缩略图图片

POM文件添加Maven依赖

		<dependency>
			<groupId>gui.ava</groupId>
			<artifactId>html2image</artifactId>
			<version>0.9</version>
		</dependency>

主要代码:

        String coverPath = null;
        try {
            HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
            imageGenerator.loadHtml(lzDocs.getContent());//也可以根据html url引用 loadUrl的方式加载
            Thread.sleep(1000); //有时会有加载图片延迟,因此这里设置下延时
            BufferedImage cover = imageGenerator.getBufferedImage();//获取图片
            cover = ImageUtils.getCoverImage(cover);//将图片转成综略图
            String coverName = UUIDGenerator.generate().toString() + ".png";
            MultipartFile mpFile = FileUtils.imageToMpFile(cover, coverName);
            coverPath = sysBaseAPI.upload(mpFile,"cover", uploadType);//上传文件到服务器

        } catch (Exception e) {
            e.printStackTrace();
        }

图片工具类,供主要代码调用

public class ImageUtils {

    /**
     * bufferedImage转InputStream
     */
    public static InputStream bufferedImageToInputStream(BufferedImage image) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (IOException e) {
        }
        return null;
    }

    /**
     * 获取图片大小信息
     */
    public static Rectangle getImgRect(BufferedImage image) throws IOException {

        Iterator readers = ImageIO.getImageReadersByFormatName("png");
        ImageReader reader = (ImageReader) readers.next();
        InputStream source = bufferedImageToInputStream(image);
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        reader.setInput(iis, true);

        int imageIndex = 0;
        return new Rectangle(0, 0, reader.getWidth(imageIndex), reader.getHeight(imageIndex));

    }

    /**
     * 图片裁剪,按指定大小裁剪
     */
    public static BufferedImage imageCut(BufferedImage image, Rectangle rect) throws IOException {

        // 取得图片读入器
        Iterator readers = ImageIO.getImageReadersByFormatName("png");
        System.out.println(readers);
        ImageReader reader = (ImageReader) readers.next();
        System.out.println(reader);

        // 取得图片读入流
        InputStream source = bufferedImageToInputStream(image);
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        reader.setInput(iis, true);

        // 图片参数
        ImageReadParam param = reader.getDefaultReadParam();
        int imageIndex = 0;
        //Rectangle rect = new Rectangle(0, 0, reader.getWidth(imageIndex), 100);
        param.setSourceRegion(rect);
        BufferedImage bi = reader.read(0, param);
        iis.close();
        source.close();
        return bi;
    }

    /**
     * 压缩图片,用于高质量图片质量降低,改变图片大小
     */
    public static BufferedImage compressImage(BufferedImage imageByte, int ppi) {
        BufferedImage smallImage = null;
        int width = 0, height = 0;

        if (imageByte == null)
            return null;

        InputStream byteInput = bufferedImageToInputStream(imageByte);
        try {
            Image image = ImageIO.read(byteInput);
            int w = image.getWidth(null);
            int h = image.getHeight(null);
            // adjust weight and height to avoid image distortion
            double scale = 0;
            scale = Math.min((float) ppi / w, (float) ppi / h);
            width = (int) (w * scale);
            width -= width % 4;
            height = (int) (h * scale);

            if (scale >= (double) 1)
                return imageByte;

            BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            buffImg.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            //ByteArrayOutputStream out = new ByteArrayOutputStream();
            //ImageIO.write(buffImg, "png", out);
            smallImage = buffImg;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return smallImage;
    }


    /**
     * 将BufferedImage转换为byte[]
     * @param image
     * @return
     */
    public static byte[] bufferedImageToByteArray(BufferedImage image) throws IOException{
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        return os.toByteArray();
    }

    /**
     * 将BufferedImage转换pdf
     */
    public static String imageToPdf(List<BufferedImage> images) throws IOException {
        log.info("图片转pdf开始===============");
        String newFile = StrUtil.uuid().replace("-", "") + ".pdf";
        PdfWriter pdfWriter = new PdfWriter( newFile);
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        Document document = new Document(pdfDocument);
        for (BufferedImage image : images) {
            byte[] data = bufferedImageToByteArray(image);
            com.itextpdf.layout.element.Image img = new com.itextpdf.layout.element.Image(ImageDataFactory.createPng(data));
            document.add(img);
        }
        document.close();
        log.info("图片转pdf结束===============");
        return newFile;
    }

    /**
     * 获取缩略图图片,用作封面,按长宽比例设备,高度太高裁掉,高度太低补余白
     */
    public static BufferedImage getCoverImage (BufferedImage originalImage) throws IOException {

        BufferedImage result = null;
        // 获取图片的长宽
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();

        Rectangle rect = ImageUtils.getImgRect(originalImage);
        if (rect.getHeight() > rect.getWidth()) {
            rect.setRect(0,0, rect.getWidth(), rect.getWidth() / 1.3);
            result = ImageUtils.imageCut(originalImage, rect);
        } else {
            int newWidth = 800;
            int newHeight = 600;

            // 计算缩放比例
            double scale = Math.min((double) newWidth / originalWidth, (double) newHeight / originalHeight);

            // 计算调整后的长宽
            int scaledWidth = (int) (originalWidth * scale);
            int scaledHeight = (int) (originalHeight * scale);

            // 创建新的BufferedImage对象,添加余白
            BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = resizedImage.createGraphics();
            Color fillColor = new Color(255, 255, 255); // 白颜色
            g.setColor(fillColor);
            g.fillRect(0, 0, newWidth, newHeight);
            g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
            g.dispose();
            result = resizedImage;
        }
        return result;
    }



}


http://www.kler.cn/a/161745.html

相关文章:

  • 如何从头开始构建神经网络?(附教程)
  • mongoDB的安装及使用
  • 【p2p、分布式,区块链笔记 DAM】GUN/SEA(Security, Encryption, Authorization) 模块genkey
  • ❤React-JSX语法认识和使用
  • 【蓝桥等考C++真题】蓝桥杯等级考试C++组第13级L13真题原题(含答案)-最大的数
  • 网页web无插件播放器EasyPlayer.js点播播放器遇到视频地址播放不了的现象及措施
  • gcc安全特性之变量初始化检查
  • 二百一十、Hive——Flume采集的JSON数据文件写入Hive的ODS层表后字段的数据残缺
  • Python 适合做什么?
  • 关于popen执行命令无效,但是手动命令行执行有效的问题
  • redis查看统计信息
  • 智能优化算法应用:基于蛇优化算法无线传感器网络(WSN)覆盖优化 - 附代码
  • 题目:回文判定(蓝桥OJ 1371)
  • MacBook安装方正小标宋简体和仿宋GB2312
  • NLP自然语言处理学习笔记
  • Data Mining数据挖掘—2. Classification分类
  • 华清远见嵌入式学习——QT——作业1
  • CoreDNS实战(二)-CoreDNS+ETCD实现DNS服务发现
  • 陈睿接手一年后,B站全力一搏的游戏业务怎样了
  • ORA-01502: index ‘xxx‘ or partition of such index is in unusable state
  • Shell实操(九):判断输入内容直至指定内容退出
  • 12.Java程序设计-基于Springboot框架的Android学习生活交流APP设计与实现
  • Flume 安装部署
  • 记账中心二开
  • 二十一章网络通信
  • 【ArcGIS Pro微课1000例】0041:Pro强大的定位搜索功能、定位窗格、地图上查找地点