package com.hzfc.web.entity;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
/**
* @Description
* @Author weitj
* @Date 2022年05月07日 20:36
*/
public class Test {
public static String ss="";
public static void main(String[] args) throws IOException {
String imageStr= TransformPhotoToBase64Data();
TransformBase64DataToPhoto(readHtmlTxt());
}
/**
* @Description: 读取指定位置的配置文件
* @param
* @return: java.lang.String
* @Author: wtj
* @Date: 2022-03-18 09:00
*/
private static String readHtmlTxt(){
StringBuffer sb = new StringBuffer();
try {
FileInputStream fin = new FileInputStream("D:/1.txt");
InputStreamReader reader = null;
try {
reader = new InputStreamReader(fin,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BufferedReader buffReader = new BufferedReader(reader);
String strTmp = "";
while(true){
try {
if (!((strTmp = buffReader.readLine())!=null)) break;
} catch (IOException e) {
e.printStackTrace();
}
sb.append(strTmp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return sb.toString();
}
public static void TransformBase64DataToPhoto(String Base64Photo) throws IOException {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte [] ImgContainer = null; //图片二进制流接收器
FileOutputStream fileOutputStream = null; //文件输出流
String RealBaseData = Base64Photo.split(",")[1]; //去除掉字节信息,获取字节数据集
// String RealBaseData = Base64Photo;
//如果数据流为空,则返回提示
if(Base64Photo.equals("")){
System.out.println("图像数据流为空!");
}else{
//解码
String NoWrapData = RealBaseData.replaceAll("\n",""); //去除掉换行符
String NoSpaceData = NoWrapData.trim(); //去掉空格
ImgContainer = base64Decoder.decodeBuffer(NoSpaceData); //解码为字节数组
//字节流转文件
try {
fileOutputStream = new FileOutputStream("d:/1.jpg"); //文件输出的保存路径及名称
fileOutputStream.write(ImgContainer); //将Base64字节流写进指定文件路径
}catch (Exception e){
e.printStackTrace();
} finally {
if(fileOutputStream != null){
try{
fileOutputStream.close(); //关闭文件输出流
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
public static String TransformPhotoToBase64Data(){
BASE64Encoder encoder = new BASE64Encoder();
byte [] ImgContainer = null ; //数据集缓存器
FileInputStream fileInputStream = null; //文件输入流
try {
fileInputStream = new FileInputStream("d:/2.jpg"); //到指定路径寻找文件
ImgContainer = new byte[fileInputStream.available()]; //设置图片字节数据缓冲区大小
fileInputStream.read(ImgContainer); //将数据流中的图片数据读进缓冲区
String Base64ImgData =encoder.encode(ImgContainer); //将图片编码转换成Base64格式的数据集
fileInputStream.close(); //关闭数据流
return Base64ImgData; //将缓冲区数据转换成字符数据返回
} catch (FileNotFoundException e) {
return "找不到指定文件!";
} catch (IOException e) {
e.printStackTrace();
}
return "null";
}
}