PDF或图片转换成Base64编码

😂 这篇文章最后更新于1827天前,您需要注意相关的内容是否还可用。
目录导航
  • 图片/PDF转Base64
  • PDF转图片转Base64
    • Base64工具类
  • pdf转base64参考百度经验:https://jingyan.baidu.com/article/59a015e3770f58f7948865eb.html

    timg.jpg

    图片/PDF转Base64

    首先了解下如何最简单转base64,这里用到jdk中的BASE64Encoder,其中byte[] bytes为字节数组的文件(下列代码中是图片)

                BASE64Encoder encoder = new BASE64Encoder();
    //            encode、encodeBuffer均可,由于该方法转换的字符中含换行符
    //            因此使用replaceAll替换掉所有换行符
                String encode1 = encoder.encodeBuffer(bytes).trim().replaceAll("\r\n","");
                String encode2 = encoder.encode(bytes).trim().replaceAll("\r\n","");
    //            根据文件类型添加data:信息,例如下列是图片
    //            PDF可写成data:application/pdf;base64
                System.out.println("data:image/png;base64,"+encode2);

    如果上述byte[] bytes数组为pdf的话即添加

    data:application/pdf;base64

    前端HTML显示PDF可以用iframe引用实现

    <iframe src="data:application/pdf;base64,这里是base64主体内容" style="width:100%;height:100%"></iframe>

    如果引用base64图片则为

    <img src="data:image/png;base64,***************************************************"/>

    PDF转图片转Base64

    使用Free Spire.PDF for JAVA,官网:http://e-iceblue.cn/Downloads/Free-Spire-PDF-JAVA.html

    Free Spire.PDF for JAVA是一款完全免费的PDF Java组件,开发人员可以使用它在Java应用程序中进行创建PDF、读取PDF和保存PDF等操作,并且无需安装Adobe Acrobat。

            //加载PDF文件
            PdfDocument doc = new PdfDocument();
            doc.loadFromFile("d:/pdf/test.pdf");
            //保存PDF的每一页到图片
            BufferedImage image;
            for (int i = 0; i < doc.getPages().getCount(); i++) {
                image = doc.saveAsImage(i);
                File file = new File(String.format("d:/pdf/ToImage-img-%d.png", i));//指定图片文件
                ImageIO.write(image, "PNG", file);//写入图片到文件
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ImageIO.write(image, "png", outputStream);//也可将图片写入进流
                byte[] bytes = outputStream.toByteArray();//将流转换成byte[]
    //            下述使用工具类来进行Base64编码
                System.out.println("data:image/png;base64," + Base64Utils.encode(bytes));
            }
            doc.close();

    Base64工具类

    public class Base64Utils {
        private static char[] base64EncodeChars = new char[]
                {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                        'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                        'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
                        '6', '7', '8', '9', '+', '/'};
        private static byte[] base64DecodeChars = new byte[]
                {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,
                        54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
                        12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
                        30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
                        -1, -1, -1};
        public static String encode(byte[] data) {
            StringBuffer sb = new StringBuffer();
            int len = data.length;
            int i = 0;
            int b1, b2, b3;
            while (i < len) {
                b1 = data[i++] & 0xff;
                if (i == len) {
                    sb.append(base64EncodeChars[b1 >>> 2]);
                    sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
                    sb.append("==");
                    break;
                }
                b2 = data[i++] & 0xff;
                if (i == len) {
                    sb.append(base64EncodeChars[b1 >>> 2]);
                    sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                    sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
                    sb.append("=");
                    break;
                }
                b3 = data[i++] & 0xff;
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
                sb.append(base64EncodeChars[b3 & 0x3f]);
            }
            return sb.toString();
        }
        public static byte[] decode(String str) {
            try {
                return decodePrivate(str);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return new byte[]
                    {};
        }
        private static byte[] decodePrivate(String str) throws UnsupportedEncodingException {
            StringBuffer sb = new StringBuffer();
            byte[] data = null;
            data = str.getBytes("US-ASCII");
            int len = data.length;
            int i = 0;
            int b1, b2, b3, b4;
            while (i < len) {
                do {
                    b1 = base64DecodeChars[data[i++]];
                } while (i < len && b1 == -1);
                if (b1 == -1)
                    break;
                do {
                    b2 = base64DecodeChars[data[i++]];
                } while (i < len && b2 == -1);
                if (b2 == -1)
                    break;
                sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
                do {
                    b3 = data[i++];
                    if (b3 == 61)
                        return sb.toString().getBytes("iso8859-1");
                    b3 = base64DecodeChars[b3];
                } while (i < len && b3 == -1);
                if (b3 == -1)
                    break;
                sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
                do {
                    b4 = data[i++];
                    if (b4 == 61)
                        return sb.toString().getBytes("iso8859-1");
                    b4 = base64DecodeChars[b4];
                } while (i < len && b4 == -1);
                if (b4 == -1)
                    break;
                sb.append((char) (((b3 & 0x03) << 6) | b4));
            }
            return sb.toString().getBytes("iso8859-1");
        }
    }

    或者使用itext包效果一样,依赖如下:

    <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.13</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.12</version>
    </dependency>

    代码如下:

    import com.itextpdf.text.pdf.PdfReader;
    import org.apache.pdfbox.pdmodel.PDDocument;
    import org.apache.pdfbox.rendering.PDFRenderer;
    import sun.misc.BASE64Encoder;
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.*;
    
    public class TEXT {
        public static void main(String[] args) throws IOException {
            String path = "D:/a.pdf";
            File file = new File(path);
            BASE64Encoder encoder = new sun.misc.BASE64Encoder();
            FileInputStream is=new FileInputStream(file);
            byte[] pdf=new byte[is.available()];
            is.read(pdf);
            is.close();
            PDDocument pdDocument = PDDocument.load(pdf);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            PdfReader reader = new PdfReader(pdf);
            int pageNum = reader.getNumberOfPages();
            for (int j = 0; j < pageNum; j++) {
                BufferedImage image = renderer.renderImageWithDPI(j, 100);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "png", baos);
                baos.flush();
                byte[] imageInByte = baos.toByteArray();
                String base64 = encoder.encode(imageInByte).trim().replaceAll("\r\n","");
                baos.close();
                System.out.println("data:image/png;base64,"+base64);
            }
            reader.close();
        }
    }