将pdf的base64编码格式转为img的base64编码格式

通过pdf的base64编码格式直接转为img的base64编码格式:

public static String base64PdfToJpgBase64(String base64Pdf) {
        if (StrUtil.isEmpty(base64Pdf)){
            return null;
        }
        String jpg_base64 = null;
        int pdfdpi = 200;
        Base64Decoder decoder = new Base64Decoder();
        try {
            // Base64解码
            byte[] pdf_bytes = decoder.decode(base64Pdf);
            PDDocument doc = PDDocument.load(pdf_bytes);
            int size = doc.getNumberOfPages();
            for (int i = 0; i < size; i++) {
                BufferedImage image = new PDFRenderer(doc).renderImageWithDPI(i, pdfdpi, ImageType.RGB);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
                ImageIO.write(image, "jpg", baos);//写入流中
                byte[] jpg_Bytes = baos.toByteArray();//转换成字节
                BASE64Encoder encoder = new BASE64Encoder();
                jpg_base64 = encoder.encodeBuffer(jpg_Bytes).trim();//转换成base64串
                jpg_base64 = jpg_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
            }
//            baos.close();
            doc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jpg_base64;
    }

你可能感兴趣的:(java)