java图片转pdf ,pdf 导出,pdf转图片

java服务端生成带echars图片的word 最近项目有个需求 :服务器定时跑数据生成分析图并导出word文档。附加word转pdf功能。 首先,关于服务器端(java)生成echars图片。 原理:通过无头浏览器调用js方法,使用服务端查出来的数据生成echars图片,此处使用了phantomjs作为无头浏览器(此开源项目目前处于终止状态,谷歌浏览器等都开发出类似功能,源码贡献者成员之一终止继续更新版本)。下附详细代码。 packa... 阅读详情

pom引入jar

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.0-RC2</version>
        </dependency>

转pdf方法

/**
     * 使用pdfbox将jpg转成pdf
     *
     * @throws IOException IOException
     */
    public byte[] jpgToPdf(MultipartFile file) throws IOException {
//        long old = System.currentTimeMillis();
//        System.out.println(" -- 图片转PDF:" + simpleDateFormat.format(old) + " 开始处理 -- " + fileAbsolutePath);

        byte[] pdfBytes = new byte[0]; // PDF Bytes
        InputStream jpgStream = file.getInputStream();
        PDDocument pdDocument = new PDDocument();
        BufferedImage image = ImageIO.read(jpgStream);

        PDPage pdPage = new PDPage(new PDRectangle(image.getWidth(), image.getHeight()));
        pdDocument.addPage(pdPage);
        PDImageXObject pdImageXObject = LosslessFactory.createFromImage(pdDocument, image);
        PDPageContentStream contentStream = new PDPageContentStream(pdDocument, pdPage);
        try {

            contentStream.drawImage(pdImageXObject, 0, 0, image.getWidth(), image.getHeight());
            contentStream.close();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PDAcroForm acroForm = pdDocument.getDocumentCatalog().getAcroForm();
            if (acroForm != null) {
                PDTextField field = (PDTextField) acroForm.getField("sampleField");
                field.setValue("Text Entry");
            }

            pdDocument.save(baos);
            pdfBytes = baos.toByteArray();
//        String newFilePath = fileAbsolutePath.substring(0, fileAbsolutePath.lastIndexOf(".")) + ".pdf";
//        pdDocument.save(newFilePath);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (pdDocument != null) {
                try {
                    pdDocument.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (jpgStream != null) {
                try {
                    jpgStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        long now = System.currentTimeMillis();
//        File file = new File(fileAbsolutePath);
//        boolean delete = file.delete();
//        System.out.println(" -- 图片转PDF处理结束时间:" + " 处理结束 -- 删除原始文件 " + delete);
        return pdfBytes;

    }

导出方法

 @Override
    public String plantPhotoDownload(DvsPlantPhoto dvsPlantPhoto, HttpServletResponse response, HttpServletRequest request) throws Exception {
        DvsPlantPhoto result = this.getOne(new QueryWrapper<>(dvsPlantPhoto));
        if (result != null) {
            String uri = result.getKey();
            BlobServiceClient blobServiceClient = BlobUtils.getBlobServiceClient();
            BlobContainerClient a = BlobUtils.getContainer(blobServiceClient, containerName);
            ByteArrayOutputStream byteArrayOutputStream = BlobUtils.downBlobFilecao(a, uri);
//            return Base64.getEncoder().encodeToString(aa);

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

            response.setCharacterEncoding(request.getCharacterEncoding());
            response.setContentType("application/pdf");
            try {
                response.setHeader("Content-Disposition", "attachment; filename=" + result.getKey());
                IOUtils.copy(byteArrayInputStream, response.getOutputStream());
                response.flushBuffer();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            } finally {
                if (byteArrayInputStream != null) {
                    try {
                        byteArrayInputStream.close();
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                }
                if (byteArrayOutputStream != null) {
                    try {
                        byteArrayOutputStream.close();
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
            return new JSONObject().toJSONString();
        } else {
            return new JSONObject().toJSONString();
        }
    }

二 另一个图片转pDf办法

   <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.sejda.imageio</groupId>
            <artifactId>webp-imageio</artifactId>
            <version>0.1.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.8</version>
        </dependency>
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;


@Component
public class PdfUtils {

    /**
     * 将图片转换为PDF文件
     *
     * @param file SpringMVC获取的图片文件
     * @return PDF文件流
     * @throws IOException       IO异常
     * @throws DocumentException PDF文档异常
     */
    public static byte[] getPdfFile(MultipartFile file) throws DocumentException, IOException {
        File pdf = generatePdfFile(file);
        byte[] fileByte = FileUtils.readFileToByteArray(pdf);
        pdf.delete();
        return fileByte;
    }

    /**
     * 将图片转换为PDF文件
     *
     * @param file SpringMVC获取的图片文件
     * @return PDF文件
     * @throws IOException       IO异常
     * @throws DocumentException PDF文档异常
     */
    public static File generatePdfFile(MultipartFile file) throws IOException, DocumentException {
        File pdf = new File(SnowFlake.nextId() + "test.pdf");
        Document doc = new Document(PageSize.A4, 10, 10, 10, 10);
        PdfWriter.getInstance(doc, new FileOutputStream(pdf));
        doc.open();
        doc.newPage();
        Image image = null;
        float height = 0;
        float width = 0;
        try {
            image = Image.getInstance(file.getBytes());
            width = image.getWidth();
            height = image.getHeight();
        } catch (Exception e) {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", outputStream);
            image = Image.getInstance(outputStream.toByteArray());
            height = bufferedImage.getHeight();
            width = bufferedImage.getWidth();
        }
        int percent = getPercent(height, width);
        image.setAlignment(Image.MIDDLE);
        image.scalePercent(percent);
        doc.add(image);
        doc.close();
        return pdf;
    }

    /**
     * 等比压缩,获取压缩百分比
     *
     * @param height 图片的高度
     * @param weight 图片的宽度
     * @return 压缩百分比
     */
    private static int getPercent(float height, float weight) {
        float percent = 0.0F;
        if (height > weight) {
            percent = PageSize.A4.getHeight() / height * 100;
        } else {
            percent = PageSize.A4.getWidth() / weight * 100;
        }
        return Math.round(percent);
    }

}
 /**
     * @param arrayList
     * @param byteArrayInputStream
     * @Description pdf page转 图片
     * @author caohong
     * @date 8:35 AM 9/27/2023
     */
    public static void pdfConvertImage(ArrayList arrayList, ByteArrayInputStream byteArrayInputStream) throws IOException {
        // 加载PDF文档
        PDDocument document = PDDocument.load(byteArrayInputStream);
        try {
            // 创建PDFRenderer对象
            PDFRenderer renderer = new PDFRenderer(document);
            // 遍历每个页面,并将其转换为图片
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                //中间的参数是设置图片大小的
                BufferedImage image = renderer.renderImageWithDPI(0, 300, ImageType.RGB);
                ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream();
                ImageIO.write(image, "jpg", imageOutputStream);
                String s = Base64.getEncoder().encodeToString(imageOutputStream.toByteArray());
                arrayList.add(s);
                imageOutputStream.flush();
                imageOutputStream.close();
            }
        } finally {
            if(document != null){
                // 关闭文档
                document.close();
            }
        }
    }


    /**
     * @param arrayList
     * @param byteArrayInputStream
     * @Description pdf 提取 图片
     * @author caohong
     * @date 8:35 AM 9/27/2023
     */
    public static boolean extractImages(ArrayList arrayList, ByteArrayInputStream byteArrayInputStream) {
        boolean result = true;
        try {
            //通过文件名加载文档
            PDDocument document = PDDocument.load(byteArrayInputStream);
            PDPageTree pages = document.getPages();
            Iterator<PDPage> iter = pages.iterator();
            while (iter.hasNext()) {
                PDPage page = iter.next();
                PDResources resources = page.getResources();
                resources.getXObjectNames().forEach(e -> {
                    try {
                        if (resources.isImageXObject(e)) {
                            PDImageXObject imageXObject = (PDImageXObject) resources.getXObject(e);
                            BufferedImage bufferedImage = imageXObject.getImage();
                            System.out.println(bufferedImage);
                            ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream();
                            ImageIO.write(bufferedImage, "jpg", imageOutputStream);
                            String s = Base64.getEncoder().encodeToString(imageOutputStream.toByteArray());
                            arrayList.add(s);
                            imageOutputStream.flush();
                            imageOutputStream.close();
                        }
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                });
            }
            document.close();
            byteArrayInputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }
        return result;
    }

SpringBoot+MD2File避坑指南:Markdown转PDF时图片和列表丢失怎么办? 本文针对SpringBoot项目中MD2File库在Markdown转PDF时常见的图片丢失、列表格式混乱等问题,深入剖析了其局限性,并提供了Pandoc、wkhtmltopdf、iText及无头浏览器等多种企业级替代方案。文章详细对比了各方案的优缺点、部署方式与适用场景,并给出了包含异步处理、缓存策略和错误恢复的完整SpringBoot服务实现指南,帮助开发者构建健壮的文档导出功能。 阅读详情

相关推荐

Poi-tl图片插入终极指南:从显示不全到完美适配Word/PDF导出

本文详细解析了Poi-tl在Word/PDF文档生成中处理图片显示不全问题的终极解决方案。通过核心机制分析、五大实战方案和兼容性优化,帮助开发者实现图片完美适配,特别针对金融报告等场景提供可靠的技术保障。

weixin_26833939的博客 407

java将图片转化为pdf并输出

java将图片转化为pdf并输出

leese233的博客 5878

java PDF模板生成并导出(文字、表格、图片)

1:jar包 <!-- itextpdf--> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>

qq_43035664的博客 1万+

java实现图片转PDF

java实现图片转pdf,支持本地单个,本地批量,图片链接

gfdedexdcf的博客 3681

Java实战:用EasyExcel 3.3.2给Excel添加动态水印(附PDF转换避坑指南)

本文详细介绍了如何使用Java和EasyExcel 3.3.2为Excel文件添加动态水印,并重点解决了水印在Excel转PDF时消失的常见问题。通过结合Graphics2D生成灵活可配置的水印图片,并利用EasyExcel的SheetWriteHandler机制进行集成,文章提供了从基础实现到PDF转换避坑的完整实战指南。

weixin_29209805的博客 353

Java实现图片转换为PDF的完整指南

本文还有配套的精品资源,点击获取 简介:在Java中,使用iText库将图片转换成PDF文件是一个实用需求,尤其在文档管理和电子出版领域。文章详细介绍了使用iText进行图片转PDF的基本流程,包括引入库依赖、创建PDF文档、写入PDF流、添加图片以及最终关闭文档的步骤。此外,还提供了一个处理多个图片并动态添加到PDF中的示例,探讨了性能优化和图像预处理的相关内容。 ...

weixin_35756892的博客 3775

Java itext实现图片转pdf

一.引入pom依赖 <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.4.2</version> </dependency> 二.创建图片转pdf的实现类 p...

dong__优快云的博客 2993

Java实现HTML转PDF完整Demo项目实战

在现代Web应用中,将HTML内容精准转化为PDF格式已成为报表生成、电子发票和文档归档等场景的核心需求。随着前端页面日益复杂,包含CSS样式、JavaScript动态渲染及多媒体资源,传统静态转换方法已难以满足高质量输出要求。当前主流技术路径主要包括:基于Headless浏览器(如Puppeteer)的渲染方案,服务端解析库(如iText、Flying Saucer)的直接解析,以及结合前后端协作的混合架构。

weixin_42596214的博客 664

Java生成pdf长图(多图片转长图,铺满宽度,可实现图片缩放)

今天搞了个Java多个图片合并生成pdf长图,感觉还不错,分享给大家。需要注意的是,每个图片的宽一定要一致不然会出现黑条填充。

qq_45699784的博客 2220

Tartancalib标定OAK-FFC_4p(上)

1.使用Tartancalib标定双目或多目相机前,先对单个相机标定获得内参,再获得外参。

qq_51731421的博客 1277

别再手动写ZPL了!用C#和斑马官方SDK搞定ZT410 RFID打印机(附中文乱码解决方案)

本文详细介绍了如何使用C#和斑马官方SDK驱动ZT410 RFID打印机,解决中文乱码和RFID数据写入等常见问题。通过实战指南,开发者可以快速掌握从基础连接到高级调试的全流程,提升打印效率和可靠性。特别适用于物流、零售和资产管理领域的应用。

weixin_29267307的博客 226

java word转pdf,docx4j转pdf,docx4j导出pdf乱码,docx4j导出pdf丢失插画和图片,aspose将word转pdf 一共两种方法

docx4j转pdf,aspose转pdf,docx4j导出pdf乱码,docx4j导出pdf丢失插画和图片

zbh1957282580的博客 3346

400G光模块测试全攻略:从PCS层到CMIS合规的避坑指南

本文为网络设备测试工程师和光通信研发人员提供了一份详尽的400G光模块测试实战指南。文章深入剖析了从PCS层信号完整性、FEC容限到CMIS管理接口合规性测试的全流程,并分享了ANLT协议分析、SerDes眼图调试以及系统级流量压力测试中的核心技巧与常见避坑点,旨在帮助读者构建一套高效、精准的测试体系,确保高速光模块的可靠性与性能。

weixin_29300931的博客 215

Java操作pdf文件大全(持续更新)

注意,wps编辑表单需要会员,可以使用其他软件(Adobe Acrobat Pro或者福昕等)(1)我们使用wps打开原始PDF。

秃了也弱了 2888

Ubuntu20.04配置PX4环境启动或编译jmavsim 出现的错误及解决办法

错误1:ant命令未找到

Iamsonice的博客 8856

FPGA&ASIC笔面试题(四):编写Verilog代码描述跨时钟域信号传输,快时钟域到慢时钟域(补充)

      跨时钟域处理从快时钟域到慢时钟域,如果是下面第一个图,cklb则可以采样到signal_a_in,但是如果只有单脉冲,如第二个图,则不能确保采样掉signal_a_in。这个时候用两级触发器同步是没有用的。 代码如下: //Synchronous module Sync_Pulse( input clka, input clkb, input rst_n, input pulse_ina, output pulse_outb, ou

千歌叹尽执夏的博客 2511

JAVA根据PDF文件生成图片

PDF文件生成图片 实现功能 根据上传的PDF文件,生成图片文件, 单页PDF,生成图片文件. 多页PDF,则生成zip压缩包. 一 : 文件生成效果 二 : 引入所需maven依赖 项目采用springboot框架 <!-- PDF转图片 --> <dependency> <groupId>org.icepdf.os</groupId> <artifactId>icepdf-core</art

qq_38254635的博客 3447

YOLOv11【第三章:高阶应用与落地篇·第7节】多任务联合训练(Multi-Task Learning):检测+分割+关键点三头并进!

🏆 本文收录于专栏 《YOLOv11实战:从入门到深度优化》。本专栏围绕 YOLOv11 的改进、训练、部署与工程优化 展开,系统梳理并复现当前主流的 YOLOv11 实战案例与优化方案,内容目前已覆盖 分类、检测、分割、追踪、关键点、OBB 检测 等多个方向。

**My Coding Family** 731

解决Aspose.Words导出PDF图片异常问题

如果导出的PDF中包含图片;并且图片导出会出现异常无法正常展示时;则需要额外引用另一个jar包。

qq_61666121的博客 1193

ISP 芯片作为独立设备节点的驱动实现要点:多平台结构差异与工程部署策略解析

随着 ISP(Image Signal Processor)从 SoC 集成形态向独立芯片模块演进,在多摄系统、高动态场景、AI 图像前处理等需求下,ISP 作为单独设备节点进行驱动设计已成为主流趋势。尤其在多 SoC 平台(如高通、联发科、展锐、Rockchip)中,不同厂商对 ISP 的抽象方式与驱动接口处理存在显著差异。本文以实际工程为基础,从 Linux 内核下的设备注册流程、media\_entity 配置、VideoDevice 分配、数据 DMA 管理、与 sensor 的流同步控制等关键点展

努力分享一些人工智能、计算机视觉、影像等相关的知识干货! 1465

Android 12.0 kenel中修改rom系统内部存储的大小

在12.0的系统rom产品开发定制中,在对一些产品开发中的配置需求方面,由于在产品后续订单中,有些产品是出口的,但是硬件方面已经定板,时间比较仓促,所以 就需要软件方面在rom内部存储的大小方面作假,修改rom真实的大小容量,所以就需要在kenel驱动部分来修改这部分的值最好了,接下来分析下计算rom容量的 相关代码,然后做出相关的修改,来实现功能

安卓兼职framework和app工程师的博客 1678

Java实现Html转PDF

文章目录[隐藏]Java实现Html转PDF 原 Java实现Html转PDF 2015年07月07日 10:35:10 死神的丧钟 阅读数:38929 标签: Java HTML转PDF 更多 个人分类: Web Java 项目上的客户提出一个需求,把政务流程中的表单数据导出成pdf或者图片格式,用来作电子档案材料。表单基于公司的电子政务构建平台实现,在数据库保存的都是html格式,因此...

不知名的研发小码农 203

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Java实现PDF转图片:一张长图或每页单独保存(附完整代码)

本文介绍如何使用Java和Apache PDFBox库实现PDF转图片功能,包含两种转换方式:生成一张纵向长图和每页保存为独立图片。文章提供了完整的工具类代码,支持设置DPI控制图片清晰度,并详细注释了核心逻辑。转换长图时会自动垂直拼接所有页面并水平居中,转换单页图片时按页码命名(1.png,2.png...)。代码已添加文件存在性检查和异常处理,开箱即用,只需修改文件路径即可运行。

cqscf的博客 724

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Linux和Windows的word模板导出转PDF下载保姆级教程,含PDF图片处理

本文介绍了Windows和Linux系统下Word转PDF功能的实现方案。在Windows环境下使用documents4j库进行转换,通过Maven引入相关依赖;Linux系统则基于LibreOffice实现,需先安装中文语言包和字体配置。文章详细说明了参数填充、模板处理、文件转换等核心流程,并提供了PdfUtils和WordUtil两个工具类的完整代码实现。针对Linux系统特别说明了环境部署步骤,包括安装LibreOffice、设置中文字体、配置权限等。最后还介绍了PDF中图片处理的实现方法,包括图片流

weixin_43398098的博客 551

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Java 裁剪 PDF 页面:高效处理与图片输出实践

在日常的软件开发和数据处理中,PDF文档因其跨平台、版式固定等特性,被广泛应用于各类业务场景。然而,有时我们可能需要对PDF页面进行精细化操作,例如去除扫描件的空白边缘、提取页面中的特定区域作为独立内容,或者为了适应特定显示设备而裁剪页面。这些需求都指向了PDF页面裁剪这一核心功能。

2503_93068783的博客 569
上一篇: Nginx配置成系统服务,Nginx命令配置到系统环境
下一篇: Kafka集群的安装与配置(一)
ole_triangle_java
博客等级 码龄10年 82粉丝 83原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值