java to realize the mutual transformation between picture file and Base64

When uploading images through form forms, sometimes the limitation of web container on file size will affect our upload. At this time, the front-end page can consider converting the image into base64 string to achieve upload.

 

In fact, the mutual conversion between images and Base64 takes advantage of the mutual conversion between file stream and Base64.

 

Convert file to Base64 string: read file stream, put it into byte array, Base64 code byte array and return string.

Convert Base64 string to file: decode Base64 string to get byte array, and write byte data to file using file output stream.

 

Talk is cheap, show me the code. Direct code:

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class ImageBase64Converter {
    /**
     * Convert local files (pictures, excel, etc.) to Base64 strings
     *
     * @param imgPath     
     */
    public static String convertFileToBase64(String imgPath) {
        byte[] data = null;
        // Read image byte array
        try {
            InputStream in = new FileInputStream(imgPath);
            System.out.println("File size (bytes)="+in.available());
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // On byte array Base64 Code, get Base64 Encoded string
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Str = encoder.encode(data);
        return base64Str;
    }

    /**
     * Base 64 string, generate file
     */
    public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {

        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {//Determine whether the file directory exists
                dir.mkdirs();
            }

            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bfile = decoder.decodeBuffer(fileBase64String);

            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

}

 

test:

public static void main(String[] args) {
        long start = System.currentTimeMillis();
        String imgBase64Str= ImageBase64Converter.convertFileToBase64("C:\\Users\\zhangguozhan\\Pictures\\science and technology\\liziqi-Plum seven red.jpg");
//        System.out.println("Local picture conversion Base64:" + imgBase64Str);
        System.out.println("Base64 Character string length="+imgBase64Str.length());
        ImageBase64Converter.convertBase64ToFile(imgBase64Str,"C:\\Users\\zhangguozhan\\Pictures\\science and technology","test.jpg");
        System.out.println("duration:"+(System.currentTimeMillis()-start));

        start=System.currentTimeMillis();
        String fileBase64Str= ImageBase64Converter.convertFileToBase64("C:\\Users\\zhangguozhan\\Pictures\\science and technology\\PayOrderList200109075516581.xlsx");
//        System.out.println("local excel Transformation Base64:" + fileBase64Str);
        System.out.println("size="+fileBase64Str.length());
        ImageBase64Converter.convertBase64ToFile(fileBase64Str,"C:\\Users\\zhangguozhan\\Pictures\\science and technology","test.xlsx");
        System.out.println("duration:"+(System.currentTimeMillis()-start));

    }

 

Execution result:

File size in bytes = 2820811
Base64 string length=3860058
duration:244
File size in bytes = 25506
size=34902
duration:10

 

 

Note: to get the size of the File, use the available() method of the FileInputStream instance, and use the length() of the File instance to return 0.

As shown in the following figure, the size of the picture file "liziqi plum seven burst red. jpg" in the test method is exactly 2820811 bytes ÷ 1024 = 2755 KB ÷ 1024=2.68M

Tags: Java Excel

Posted on Fri, 10 Jan 2020 09:07:21 -0500 by beyzad