image base64 encoding

image base64 encoding

1. Image base64 description

The base64 encoding of a picture is to encode a picture data into a string of strings, and use the string to replace
the common base64 picture introduction method of the image address url in the front-end page:

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

1. Advantages
(1) The images in base64 format are in text format, occupying less memory , and the size ratio after conversion is about 1/3, which reduces the consumption of resource servers;
(2) When using images in base64 format in web pages, there is no need to Requesting the server to call image resources reduces the number of server visits .

2. Disadvantages (1) There is a lot of text content in base64 format, which increases the pressure on the database server
when stored in the database ; (2) Although there is no need to access the server for web page loading pictures, but because there is too much content in base64 format, the web page is loaded. The speed will be reduced , which may affect the user's experience.

2. Image base64 tool class

Add tool class in common-util module
Add com.atguigu.yygh.common.util.ImageBase64Util class

package com.atguigu.yygh.common.util;

import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class ImageBase64Util {
    
    

public static void main(String[] args) {
    
    
        String imageFile= "D:\\yygh_work\\xh.png";// 待处理的图片
System.out.println(getImageString(imageFile));
    }

public static String getImageString(String imageFile){
    
    
        InputStream is = null;
try {
    
    
byte[] data = null;
            is = new FileInputStream(new File(imageFile));
            data = new byte[is.available()];
            is.read(data);
return new String(Base64.encodeBase64(data));
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
if (null != is) {
    
    
try {
    
    
                    is.close();
                    is = null;
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            }
        }
return "";
    }
}

Guess you like

Origin blog.csdn.net/david2000999/article/details/122503824