• Base64对图片的加解密


    Base64对图片的加解密:

    什么是base64?

     百度百科中对Base64有一个很好的解释:“Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法”。

            什么是“可打印字符”呢?为什么要用它来传输8Bit字节码呢?在回答这两个问题之前我们有必要来思考一下什么情况下需要使用到Base64?Base64一般用于在HTTP协议下传输二进制数据,由于HTTP协议是文本协议,所以在HTTP协议下传输二进制数据需要将二进制数据转换为字符数据。然而直接转换是不行的。因为网络传输只能传输可打印字符。什么是可打印字符?在ASCII码中规定,0~31、127这33个字符属于控制字符,32~126这95个字符属于可打印字符,也就是说网络传输只能传输这95个字符,不在这个范围内的字符无法传输。那么该怎么才能传输其他字符呢?其中一种方式就是使用Base64。

            Base64,就是使用64个可打印字符来表示二进制数据的方法。Base64的索引与对应字符的关系如下表所示:

    二、Java中实现Base64

    Java已经替我们写好Base64的实现细节,使用的时候直接调用即可。

    三、Java实现Base64转pdf

    所需要的依赖:

    <dependencies>
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itext-asian</artifactId>
                <version>5.2.0</version>
            </dependency>
            <dependency>
                <groupId>org.apache.pdfbox</groupId>
                <artifactId>pdfbox</artifactId>
                <version>2.0.18</version>
            </dependency>
            <dependency>
                <groupId>com.itextpdf</groupId>
                <artifactId>itextpdf</artifactId>
                <version>5.5.13.1</version>
            </dependency>
        </dependencies>
    

      如若不是maven项目所需jar包如下:

      public static void base64StringToPdf(String base64Content, String filePath) {
            BASE64Decoder decoder = new BASE64Decoder();
            BufferedInputStream bis = null;
            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
    
            try {
                byte[] bytes = decoder.decodeBuffer(base64Content);//base64编码内容转换为字节数组
                ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
                bis = new BufferedInputStream(byteInputStream);
                File file = new File(filePath);
                File path = file.getParentFile();
                if (!path.exists()) {
                    path.mkdirs();
                }
                fos = new FileOutputStream(file);
                bos = new BufferedOutputStream(fos);
    
                byte[] buffer = new byte[1024];
                int length = bis.read(buffer);
                while (length != -1) {
                    bos.write(buffer, 0, length);
                    length = bis.read(buffer);
                }
                bos.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    

      测试的时候我们发现Base64码太长了,65万字符,我们可以采取流的形式,从文件夹读取内容:

    测试demo:

    public static void main(String[] args) throws Exception {
            /*
            * 读取本地文件内容
            * */
    //生成的pdf地址 String path = "D://11/11.pdf";
    //base64文件 String fileName = "D://11/22.txt"; File file = new File(fileName); if( !file.exists() ){ System.out.println("file not exist"); } FileReader fileReader = new FileReader(file); BufferedReader bReader = new BufferedReader(fileReader); String tempString = null; while ( (tempString = bReader.readLine()) != null ) { //System.out.println(tempString); base64StringToPdf(tempString,path); } bReader.close(); fileReader.close(); }

      pdf转base64(我们也可以把生成的base64码采用流的方式放到本地的某个文件中,这里我们采用打印在控制台)

     public static String PDFToBase64(File file) {
            BASE64Encoder encoder = new BASE64Encoder();
            FileInputStream fin =null;
            BufferedInputStream bin =null;
            ByteArrayOutputStream baos = null;
            BufferedOutputStream bout =null;
            try {
                fin = new FileInputStream(file);
                bin = new BufferedInputStream(fin);
                baos = new ByteArrayOutputStream();
                bout = new BufferedOutputStream(baos);
                byte[] buffer = new byte[1024];
                int len = bin.read(buffer);
                while(len != -1){
                    bout.write(buffer, 0, len);
                    len = bin.read(buffer);
                }
                //刷新此输出流并强制写出所有缓冲的输出字节
                bout.flush();
                byte[] bytes = baos.toByteArray();
                return encoder.encodeBuffer(bytes).trim();
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {
                    fin.close();
                    bin.close();
                    bout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    

      这里我记录一下工作中遇到的问题(第三方送过来PDFbase64然后在我这里处理成png的base64然后以json的格式送给那台)

    1:解密成PDF就不要在这里多说了,百度上一大堆公共方法

    2:把PDF转PNG然后加密

    3:全部删除

     /**
         * 将多页pdf转化为多张图片
         * @param pdfPath
         * @return
         * @throws
         * @author:dup
         */
        public static List<String> pdfPathToImagePaths(String pdfPath){
            File pdfFile = new File(pdfPath);
            PDDocument pdDocument;
            try {
                pdDocument = PDDocument.load(pdfFile);
                int pageCount = pdDocument.getNumberOfPages();
                PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
                List<String> imagePathList = new ArrayList<>();
                String fileParent = pdfFile.getParent();
                for(int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
                    String imgPath = fileParent + File.separator + UUID.randomUUID().toString() + ".png";
                    BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, 105,ImageType.RGB);
                    ImageIO.write(image, "png", new File(imgPath));
                    imagePathList.add(imgPath);
                }
                pdDocument.close();
                return imagePathList;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    

      

     /*
        * png转base64
        * */
        public static String ImageToBase64ByLocal(String imgFile){
            InputStream in=null;
            byte[]data=null;
            // 读取图片字节数组
            try{
                in=new FileInputStream(imgFile);
                data=new byte[in.available()];
                in.read(data);
                in.close();
            }catch(IOException e){
                e.printStackTrace();
            }
            // 对字节数组Base64编码
            BASE64Encoder encoder=new BASE64Encoder();
            return encoder.encode(data);// 返回Base64编码过的字节数组字符串
        }
    

      

    public class DeleteFile {
        private final static String FS = System.getProperty("file.separator");
        private static final String IMG_PATH= "D:/111";
        private static boolean running = false;
        public static void main(String[] args) {
            if (!running ) {
                System.out.println("删除图片开始");
                running = true;
                System.out.println("开始执行,图片路径为"+IMG_PATH);
                File fileTemp = new File(IMG_PATH);
                // 判断文件是否存在
                boolean falg = false;
                falg = fileTemp.exists();
                if(falg){
                    System.out.println("文件存在");
                    if(true==fileTemp.isDirectory()){
                        System.out.println("temp文件是个目录");
                        String[] png = fileTemp.list();
                        for (int i = 0; i < png.length; i++) {
                            String [] ll = new String[]{"png","pdf","jpg","jpeg"};
                            for (int j = 0; j <ll.length ; j++) {
                                if (true == png[i].endsWith(ll[j])) {
                                    File file = new File(IMG_PATH+FS+ png[i]);
                                    if (true == file.isFile()) {
                                        boolean flag = false;
                                        flag = file.delete();
                                        if (flag) {
                                            System.out.println("成功删除无效图片文件:" + file.getName());
                                        }
                                        else {
                                            System.out.println("删除失败");
                                        }
                                    }
                                }
                            }
    
                    }
                }
    
            }
    
        }
        }
    }
    

      测试:

     

     最终把所有的码放到对象里,送给前台即可。

  • 相关阅读:
    二分查找
    bracketed-paste-magic:zle:41: not enough arguments for -U
    逗号表达式返回值
    requestAnimationFrame实现一帧的函数节流
    phaser常用API总结
    table表头固定问题
    接口防刷的方法
    雪碧图background-position的rem用法
    sphinx 增量索引与主索引使用测试
    msysgit ls 中文显示
  • 原文地址:https://www.cnblogs.com/dp06134816-login/p/13266107.html
Copyright © 2020-2023  润新知