Base64 conversion image, image conversion Base64 example

1. The following is a complete code example.
Convert the specified file path to binary
Convert network images to binary
Convert base64 to image resources

package com.xxx.example.file;
 
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
 
import javax.imageio.ImageIO;
 
import com.zxtc.syonline.support.common.StringUtil;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
public class ImageBioChangeUtil {
    
    static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
    static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
    
    //Get the image from the file path and convert it to binary
    public static String getImageBinary(String filePath){
        if(StringUtil.isEmpty(filePath)) {
            return null;
        }
        File f = new File(filePath); //Gif animation is not allowed here. Although the gif format can be output later, it is not an animation.
        BufferedImage bi;
        try {
            bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            byte[] bytes = baos.toByteArray();
               
            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    //Get the image from URl and convert it to binary
    public static String getImageBinaryFromUrl(String urlPath) throws Exception{
        if(StringUtil.isEmpty(urlPath)) {
            return "";
        }
        URL url=new URL(urlPath);
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(3000);//Timeout prompt 1 second = 1000 milliseconds
        InputStream inStream=conn.getInputStream();//Get the output stream
        byte[] data=readInputStream(inStream);
        return encoder.encodeBuffer(data).trim();
        
    }
     //readInputStream method
    private static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream=new ByteArrayOutputStream();
        byte[] buffer=new byte[1024];//convert to binary
        int len=0;
        while((len =inStream.read(buffer))!=-1){
            outStream.write(buffer,0,len);
        }
        return outStream.toByteArray();
    }
    //Convert binary to image
    public static void base64StringToImage(String base64String,String outFilePath){
        if(StringUtil.isNotEmpty(base64String) & amp; & amp;StringUtil.isNotEmpty(outFilePath)) {
            try {
                byte[] bytes1 = decoder.decodeBuffer(base64String);
                   
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
                BufferedImage bi1 =ImageIO.read(bais);
                File w2 = new File(outFilePath);//can be in jpg or png format
                if (!w2.exists()) { //If the file does not exist, create the file and create the directory first
                    File dir = new File(w2.getParent());
                    dir.mkdirs();
                    w2.createNewFile(); // Create a new file
                }
                ImageIO.write(bi1, "jpg", w2);//No matter what format of the image is output, no changes are needed here
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        String imageBinary=null;
        try {
            imageBinary = getImageBinaryFromUrl("");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(imageBinary);
        String outFilePath= "E://test//bio//zhh/aa.png";
        base64StringToImage(imageBinary,outFilePath);
    }
}

2. How to determine the format of base64 images?

//Determine the file format of the image base64 string
    public static String checkImageBase64Format(String base64ImgData) {
        byte[] b = Base64Util.decode(base64ImgData);
        String type = "";
        if (0x424D == ((b[0] & amp; 0xff) << 8 | (b[1] & amp; 0xff))) {
            type = "bmp";
        } else if (0x8950 == ((b[0] & amp; 0xff) << 8 | (b[1] & amp; 0xff))) {
            type = "png";
        } else if (0xFFD8 == ((b[0] & amp; 0xff) << 8 | (b[1] & amp; 0xff))) {
            type = "jpg";
        }
        return type;
    }

3. Convert network images to base64 strings

 /**
     * Convert the network path image to base64 format
     * @param requestUrl request network path
     * @throwsException
     */
    public static String getUrlImageToBase64(String requestUrl) throws Exception {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            //Create URL
            URL url = new URL(requestUrl);
            byte[] by = new byte[1024];
 
            //Create link
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream is = conn.getInputStream();
 
            //Read the content into memory
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
 
            // close the stream
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        // Base64 encode the byte array
        Base64.Encoder encoder = Base64.getEncoder();
// return "data:image/" + photoType + ";base64," + encoder.encodeToString(data.toByteArray());
        return encoder.encodeToString(data.toByteArray());
    }

4. Convert base64 string to image output

/**
     * Convert Base64 encoded string to file output
     * @param base64String string
     * @param path Output file saving path
     * @param fileName output file name
     * @return Whether the conversion is successful
     */
    public static boolean writeFileFromBase64(String base64String, String path, String fileName) {
        if (base64String == null){
            return false;
        }
        try {
            byte[] b = Base64Util.decode(base64String);
            File file = new File(path);
            if(!file.exists()){
                makeDir(file);
            }
            OutputStream out = new FileOutputStream(path + fileName);
            out.write(b);
            out.flush();
            out.close();
            return true;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }

Note: The input parameter of this method, the base64 format file must not have file header identification information, otherwise the conversion will fail. So here we need to judge whether header information is included.

String urlImageToBase64 = ""; //Here is the base64 string of our image
if(urlImageToBase64.indexOf(",")>-1) {//Contains header information
                System.out.println("Contains header information");
                urlImageToBase64 = urlImageToBase64.substring(urlImageToBase64.indexOf(",") + 1);
}

5. Convert the file to base64 string

/**
     * Convert the read file to Base64 encoding and return
     * @param filePath file path
     * @return base64 file
     * @throwsException
     */
    public static String readAsBase64FromFile(String filePath) {
        InputStream in = null;
        byte[] data = null;
        
        try {
            in = new FileInputStream(fileName);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
        return Base64Util.encode(data);
    }

A Base64Util.java is used above