Java模块系列:Base64(编码解码)

1 字符串转base64

package basic.datatype.datatest;

import java.util.Base64;

public class Base64Test{
    static Base64.Encoder b64Encoder = Base64.getEncoder();
    static Base64.Decoder b64Decoder = Base64.getDecoder();

    public static void main(String[] args) throws Exception{
        String dataSource = "client:123456";
        byte[] dataBytes = dataSource.getBytes("UTF-8");
        String dataEncoder = b64Encoder.encodeToString(dataBytes);
        System.out.format("Data encoder:"+dataEncoder+"\n");
        String dataDecoder = new String(b64Decoder.decode(dataEncoder), "UTF-8");
        System.out.format("Data decoder:"+dataDecoder+"\n");     
    }
}
  • 结果
Data encoder:Y2xpZW50OjEyMzQ1Ng==
Data decoder:client:123456

2 字节转base64

package com.sb.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class ImageBase64Util{
    static Base64.Encoder b64Encoder = Base64.getEncoder();
    static Base64.Decoder b64Decoder = Base64.getDecoder();

    public static String bytes2Base64(byte[] data) throws Exception{
        return b64Encoder.encodeToString(data);
    }
}

3 图像转base64

package com.sb.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class ImageBase64Util{
    static Base64.Encoder b64Encoder = Base64.getEncoder();
    static Base64.Decoder b64Decoder = Base64.getDecoder();
    public static String image2Base64(String path){
        String imgFile = path;
        InputStream in = null;
        byte[] imgBase64Byte = null;
        try{
            in = new FileInputStream(imgFile);
            imgBase64Byte = new byte[in.available()];
            in.read(imgBase64Byte);
            in.close();
        }catch(IOException e){
            e.printStackTrace();
        }
        return b64Encoder.encodeToString(imgBase64Byte);
    }
}

4 base64转为图片保存

package com.sb.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class ImageBase64Util{
    static Base64.Encoder b64Encoder = Base64.getEncoder();
    static Base64.Decoder b64Decoder = Base64.getDecoder();

    public static boolean base64ToImage(String imageBase64, String imageSavePath) throws Exception{
        if(imageBase64 == null){
            return false;
        }else{
            OutputStream out = null;
            out = new FileOutputStream(imageSavePath);
            byte[] imgBytes = b64Decoder.decode(imageBase64);
            for(int i=0;i<imgBytes.length;++i){
                if(imgBytes[i]<0){
                    imgBytes[i] += 256;
                }
            }
            out.write(imgBytes);
            return true;
        }
    }
}

5 获取URL图片

  • 工具类
package com.sb.util.https;

import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 
import java.util.Map.Entry;
import java.util.Set;
import java.util.Iterator;  
import java.util.Arrays;
import java.io.InputStream;
import java.io.FileInputStream;

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.Header;
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.util.EntityUtils;  
import org.apache.http.entity.StringEntity;

import com.sb.util.ImageBase64Util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpsClientV45Util {  
  static Logger logger = LoggerFactory.getLogger(HttpsClientV45Util.class);
  
  public static String doGetImage(HttpClient httpClient, String url, Map<String, String> paramHeader, 
      Map<String, String> paramBody) throws Exception { 
  
    String result = null;
    String imageBase64 = null; 
    String readContent = null;
    HttpGet httpGet = new HttpGet(url); 
    if(paramHeader != null){
      setHeader(httpGet, paramHeader);
    }
     
    HttpResponse response = httpClient.execute(httpGet); 
    if (response != null) { 
      HttpEntity resEntity = response.getEntity(); 
      logger.info("image entity:{}", resEntity);
      InputStream imageContent = resEntity.getContent();
      int dataLength = (int)resEntity.getContentLength();
      int dataL = imageContent.available();
      logger.info("image bytes length:{}, available:{}", dataLength, dataL);
      logger.info("image stream:{}", imageContent);

      byte[] imageBytes = new byte[dataLength];
      // logger.info("image bytes:{}", imageBytes);
      // 解决断流问题
      int readCount = 0;
      while(readCount<=dataLength){
        if(readCount == dataLength) break;
        readCount += imageContent.read(imageBytes, readCount, dataLength-readCount);
      }
      
      imageBase64 = ImageBase64Util.bytes2Base64(imageBytes);
      // logger.info("image base64:{}", imageBase64);
      if (resEntity != null) { 
        result = EntityUtils.toString(resEntity, "UTF-8"); 
      } 
    } 
    return imageBase64;
  } 
} 
  • 接口
package com.sb.controller;

import org.apache.commons.io.IOUtils;
import org.tensorflow.Graph;
import org.tensorflow.Session;
import org.tensorflow.Tensor;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.util.ResourceUtils;
import org.apache.http.client.HttpClient;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.util.Map;
import java.util.HashMap;
import com.sb.util.ImageBase64Util;
import com.sb.util.HttpClientUtil;
import com.sb.util.https.HttpsClientV45Util;
import com.sb.util.https.HttpsTrustClientV45;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@CrossOrigin(origins="*", maxAge=3600)
@RestController
@RequestMapping("/api/ai")
public class AIController{
    static Logger logger = LoggerFactory.getLogger(AIController.class);
    /**
     * 图像保存为base64编码
     * @param params
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/image-tranform2base64", method=RequestMethod.POST)
    public String imageTransfor2base64(@RequestBody Map params) throws Exception{
        if(params.containsKey("imageLocalPath")){
            String path = params.get("imageLocalPath").toString();
            return ImageBase64Util.image2Base64(path);
        }else if(params.containsKey("imageURL")){
            Map<String, String> paramHeader = new HashMap<String, String>();
            paramHeader.put("Accept", "application/json");
            String result = null;
            String imageURL = params.get("imageURL").toString();
            HttpClient httpClient = null;
            try{
                httpClient = new HttpsTrustClientV45().init();
                result = HttpsClientV45Util.doGetImage(httpClient, imageURL, paramHeader, null);
            }catch(Exception e){
                e.printStackTrace();
            }
            // logger.info("image data from url: {}",ImageBase64Util.string2Base64(result));
            return result;
            // return ImageBase64Util.string2Base64(result);
        }else{
            return "检查参数";
        }  
    }
	/**
     * 通过URL获取图像并保存
     * @param params
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/image-base64-save", method=RequestMethod.POST) 
    public String imageBase64Save(@RequestBody Map params) throws Exception{
        String imageURL = params.get("imageURL").toString();
        String imageBase64 = null;
        HttpClient httpClient = null;
        Map<String, String> paramHeader = new HashMap<String, String>();
        paramHeader.put("Accept", "application/json");
        try{
            httpClient = new HttpsTrustClientV45().init();
            imageBase64 = HttpsClientV45Util.doGetImage(httpClient, imageURL, paramHeader, null);
        }catch(Exception e){
            e.printStackTrace();
        }
        String imageSavePath = params.get("imageSavePath").toString();
        ImageBase64Util.base64ToImage(imageBase64, imageSavePath);
        return "保存成功";
    }
}

在这里插入图片描述

图5.1 图像转base64

在这里插入图片描述

图5.2 URL图像保存

【参考文献】
[1]https://www.cnblogs.com/alter888/p/9140732.html
[2]https://blog.csdn.net/hurryjiang/article/details/6688247
[3]https://blog.csdn.net/lilidejing/article/details/37913627
[4]https://www.cnblogs.com/lfyu/p/8744983.html
[5]https://www.cnblogs.com/kongxianghao/articles/6879367.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天然玩家

坚持才能做到极致

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值