图片base64编码

图片base64编码

1. 图片base64说明

图片的base64编码就是可以将一张图片数据编码成一串字符串,使用该字符串代替图像地址url
在前端页面中常见的base64图片的引入方式:

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

1.优点
(1)base64格式的图片是文本格式,占用内存小,转换后的大小比例大概为1/3,降低了资源服务器的消耗;
(2)网页中使用base64格式的图片时,不用再请求服务器调用图片资源,减少了服务器访问次数

2. 缺点
(1)base64格式的文本内容较多,存储在数据库中增大了数据库服务器的压力;
(2)网页加载图片虽然不用访问服务器了,但因为base64格式的内容太多,所以加载网页的速度会降低,可能会影响用户的体验。

2. 图片base64工具类

在common-util模块添加工具类
添加com.atguigu.yygh.common.util.ImageBase64Util类

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 "";
    }
}

猜你喜欢

转载自blog.csdn.net/david2000999/article/details/122503824