base64处理图片

介绍:

https://blog.csdn.net/u013368397/article/details/82563136

实例:

1.后台代码:base64加密与解密

imgUrl为可以访问的图片网络地址

package com.bootdo.seal.utils;

import io.netty.util.internal.StringUtil;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by jq on 2019/2/20.
 */
public class Base64 {
    /**
     * 远程读取image转换为Base64字符串
     *
     * @param imgUrl
     * @return
     */
    public static String image2Base64(String imgUrl) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        try {
            // 创建URL
            URL url = new URL(imgUrl);
            byte[] by = new byte[1024];
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();
            // 将内容读取内存中
            int len = -1;
            while ((len = is.read(by)) != -1) {
                data.write(by, 0, len);
            }
            // 关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data.toByteArray()).replaceAll("[\\s*\t\n\r]", "");
    }

    // 将base64编码字符串转换为图片(不含有data:image/jpeg;base64,这样的前缀,如果有用逗号做分割,取逗号后面的数据)
    // imgStr base64编码字符串  path 图片路径-具体到文件
    public static boolean base64ToImage(String imgStr, String path) {
        if (imgStr == null){
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(imgStr);// 解密
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0){
                    b[i] += 256;//调整异常数据
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    public static void main(String[] args) {
        //加密后字符串
        String imgStr = "";
        String imgFilePath = "F:\\doc\\new.png";
        base64ToImage(imgStr, imgFilePath);
    }

}

2.前台代码:在前台页面上使用:

<img id="img2" th:src="@{'data:image/jpg;base64,'+${base64Str}}">

base64的字符串前一定要加《  data:image/jpg;base64,  》注意:有逗号

才能被浏览器正确解析识别

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值