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

POM文件添加Maven依赖

java 复制代码
		<dependency>
			<groupId>gui.ava</groupId>
			<artifactId>html2image</artifactId>
			<version>0.9</version>
		</dependency>

主要代码:

java 复制代码
        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();
        }

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

java 复制代码
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;
    }



}
相关推荐
数据小小爬虫2 分钟前
使用Java爬虫获取淘宝商品类目API返回值
java·开发语言
lcz-200013 分钟前
IDEA一键部署SpringBoot项目到服务器
java·spring boot·intellij-idea
尘浮生14 分钟前
Java项目实战II基于微信小程序的原创音乐小程序(开发文档+数据库+源码)
java·开发语言·数据库·spring boot·微信小程序·小程序·maven
蜜桃小阿雯25 分钟前
JAVA开源项目 微服务在线教育系统 计算机毕业设计
java·开发语言·spring boot·微服务·java-ee·开源·maven
花下的晚风25 分钟前
单元测试时报错找不到@SpringBootConfiguration
java·开发语言·单元测试
卓越小Y40 分钟前
配置jellyfin docker 硬件加速
java·spring cloud·docker
白萝卜弟弟43 分钟前
【JAVA】正则表达式中的捕获组和非捕获组
java·正则表达式
袁庭新1 小时前
LuaRocks如何安装数据库驱动?
java·数据库·redis·lua·luarocks·袁庭新
hummhumm1 小时前
第 10 章 - Go语言字符串操作
java·后端·python·sql·算法·golang·database
nukix1 小时前
Mac Java 使用 tesseract 进行 ORC 识别
java·开发语言·macos·orc