integrated_traffic/src/main/java/com/zcloud/util/ImageAnd64Binary.java

138 lines
3.7 KiB
Java
Raw Normal View History

2024-01-03 09:48:43 +08:00
package com.zcloud.util;
import org.apache.commons.codec.binary.Base64;
import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* BASE64
* luoxiaobao
* www.qdkjchina.com
*/
public class ImageAnd64Binary {
public static void main(String[] args) {
String imgSrcPath = "H:/1.jpg"; // 生成64编码的图片的路径
String imgCreatePath = "H:/123.png"; // 将64编码生成图片的路径
imgCreatePath = imgCreatePath.replaceAll("\\\\", "/");
System.out.println(imgCreatePath);
String strImg = getImageStr(imgSrcPath);
System.out.println(strImg);
generateImage(strImg, imgCreatePath);
}
/**
* Base64
*
* @param imgSrcPath
* 64
* @return
*/
public static String getImageStr(String imgSrcPath) {
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(imgSrcPath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
return Base64.encodeBase64String(data);// 返回Base64编码过的字节数组字符串
}
/**
* Base64
*
* @param imgStr
*
* @param imgCreatePath
* 64
* @return
*/
public static boolean generateImage(String imgStr, String imgCreatePath) {
if (imgStr == null) // 图像数据为空
return false;
try {
// Base64解码
byte[] b = Base64.decodeBase64(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(imgCreatePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
*
*
* @param base64
*
* @return
*
* @throws IOException
*/
public static String zipBase64(String base64) throws IOException {
if (null == base64 || base64.length() <= 0) {
return base64;
}
// 创建一个新的 byte 数组输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 使用默认缓冲区大小创建新的输出流
GZIPOutputStream gzip = new GZIPOutputStream( out );
// 将 b.length 个字节写入此输出流
gzip.write( base64.getBytes() );
gzip.close();
// 使用指定的 charsetName通过解码字节将缓冲区内容转换为字符串
return out.toString( "ISO-8859-1" );
}
/**
*
*
* @param zipBase64
*
* @return
*
* @throws IOException
*/
public static String upZip(String zipBase64) throws IOException {
if (null == zipBase64 || zipBase64.length() <= 0) {
return zipBase64;
}
// 创建一个新的 byte 数组输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 创建一个 ByteArrayInputStream使用 buf 作为其缓冲区数组
2024-03-27 15:52:48 +08:00
ByteArrayInputStream in = new ByteArrayInputStream( zipBase64.getBytes( "ISO-8859-1" ) );
2024-01-03 09:48:43 +08:00
// 使用默认缓冲区大小创建新的输入流
GZIPInputStream gzip = new GZIPInputStream( in );
byte[] buffer = new byte[256];
int n = 0;
while ((n = gzip.read( buffer )) >= 0) {// 将未压缩数据读入字节数组
// 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
out.write( buffer, 0, n );
}
// 使用指定的 charsetName通过解码字节将缓冲区内容转换为字符串
return out.toString( "ISO-8859-1" );
}
}