package com.xxx.mid.utils;
import java.awt.image.RenderedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import com.XXX.mid.common.Properties;
import com.XXX.mid.utils.ftp.client.FTPClientHelper;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
/**
* 停车图片处理类
*
* @description
* @author victor
* @CreateTime 2019年1月10日 下午2:47:02
*/
@Component
public class Picture2Base64 {
private static Logger logger = LoggerFactory.getLogger(Picture2Base64.class);
// private static Pattern p = Pattern.compile("\\s*|\t|\r|\n");
private static int BUFFER_SIZE = 1024 * 1024 * 4;
private static byte[] MAX_BUFFER = new byte[BUFFER_SIZE];
private static String shareIP;
private static String picType;
// private static String nopic;
private final static String SHARE = "SHARE";
private final static String IP_AND_SHARE = "IP_AND_SHARE";
private final static String IPS_AND_SHARE = "IPS_AND_SHARE";
private final static String IP_AND_FTP = "IP_AND_FTP";
private final static String LOCAL = "LOCAL";
private final static String HTTP = "HTTP";
private final static String FTP = "FTP";
private final static String POSTTP = "posttp";
private final static String GATE_IP = "gateIP";
private static String smbMachine = "smb://";
@Autowired
private FTPClientHelper ftpClientHelper;
private static FTPClientHelper ftpClient;
@PostConstruct
public void init() {
ftpClient = this.ftpClientHelper;
shareIP = Properties.getEnt().getProperty("shareIP");
picType = Properties.getEnt().getProperty("picType");
// nopic = Properties.getEnt().getProperty("nopic");
}
public static String defaultImageStr() {
// String nopicpath = ConfKit.get("nopic");
// String defaultImageStr = getImageStr(nopic);
return "";
}
/**
* *** 从smbMachine读取文件并存储到localpath指定的路径
*
* @param smbMachine
* 共享机器的文件,如smb://xxx:xxx@10.108.23.112/myDocument/测试文本.txt,xxx:
* xxx是共享机器的用户名密码
* @param localpath
* 本地路径
* @return
*/
public static String readFromSmb(String smbMachine) {
InputStream bis = null;
String str = "";
try {
SmbFile rmifile = new SmbFile(smbMachine);
bis = new BufferedInputStream(new SmbFileInputStream(rmifile));
int length = rmifile.getContentLength();
byte[] data = new byte[length];
bis.read(data);
str = getImageStrByte(data);
return str;
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
try {
if (bis != null) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return str;
}
public static String getImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in = null;
// 读取图片字节数组
try {
in = new FileInputStream(imgFilePath);
byte[] data = getEncodedData(in);
// 对字节数组Base64编码
// Matcher m = p.matcher(Base64Utils.encodeToString(data));
// String basestr = m.replaceAll("");
// 对字节数组Base64编码
// 返回Base64编码过的字节数组字符串
return Base64Utils.encodeToString(data);
} catch (FileNotFoundException e) {
return Picture2Base64.defaultImageStr();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
/**
* 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
* @param data
* @return
*/
public static String getImageStrByte(byte[] data) {
if (Utils.isEmpty(data)) {
return Picture2Base64.defaultImageStr();
} else {
// Matcher m = p.matcher(Base64Utils.encodeToString(data));
// String basestr = m.replaceAll("");
// 返回Base64编码过的字节数组字符串
return Base64Utils.encodeToString(data);
}
}
/**
*对字节数组字符串进行Base64解码并生成图片
* @param imgStr
* @param imgFilePath
* @return
*/
public static boolean generateImage(String imgStr, String imgFilePath) {
// 图像数据为空
if (imgStr == null) {
return false;
}
try {
// Base64解码
byte[] bytes = Base64Utils.decodeFromString(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {
bytes[i] += 256;
}
}
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
public static String getHttpImageStr(String imgFilePath) {
InputStream in = null;
try {
URL url = new URL(imgFilePath);
URLConnection conn = url.openConnection();
conn.connect();
in = conn.getInputStream();
byte[] data = getEncodedData(in);
// 对字节数组Base64编码
return Base64Utils.encodeToString(data);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
public static byte[] getEncodedData(InputStream is) throws IOException {
int length = 0;
int lengthTemp = 0;
// read方法并不保证一次能读取1024*1024个字节
while (-1 != (lengthTemp = is.read(MAX_BUFFER))) {
length += lengthTemp;
if (length >= BUFFER_SIZE) {
logger.warn("读入的数据超过1024 * 1024");
break;
}
}
byte[] endodedData = new byte[length];
System.arraycopy(MAX_BUFFER, 0, endodedData, 0, length);
return endodedData;
}
/**
* 字符串转图片
*
* @param base64String
*/
public static boolean base64StringToImage(String base64String, String toImagePath, String imageType) {
try {
byte[] bytes1 = Base64Utils.decodeFromString(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
RenderedImage bi1 = ImageIO.read(bais);
// 可以是jpg,png,gif格式
File w2 = new File(toImagePath);
if (!w2.exists()) {
w2.createNewFile();
}
// 不管输出什么格式图片,此处不需改动
return ImageIO.write(bi1, imageType, w2);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 处理图片
* @param picpath
* @param record
* @return
*/
public static String dealpic(String picpath, Map<String, Object> record) {
String picstr = "";
try {
if (Boolean.parseBoolean(Properties.getEnt().getProperty(POSTTP))) {
if (Utils.isNotEmpty(picpath) && Utils.isNotEmpty(picType)) {
if (LOCAL.equals(picType)) {
// 本地图片
picstr = getImageStr(Properties.getEnt().getProperty("picpath") + picpath);
} else if (HTTP.equals(picType)) {
// HTTP 网络图片
picstr = getHttpImageStr(picpath);
} else if (SHARE.equals(picType)) {
String[] ipArr = shareIP.split(","); // 共享ip地址列表
for (int i = 0; i < ipArr.length; i++) {
SmbFile smbFile = new SmbFile("smb://" + ipArr[i] + "/" + picpath); // 获取连接
int length = smbFile.getContentLength();
if (length == 0) {
continue;
}
byte buffer[] = new byte[length];
SmbFileInputStream in = new SmbFileInputStream(smbFile);
// 建立smb文件输入流
while ((in.read(buffer)) != -1) {
picstr = Base64Util.encode(buffer);
}
in.close();
break;
}
} else if (IP_AND_SHARE.equals(picType)) {
// 单独IP + 共享文件模式;
if (record != null && record.get(GATE_IP) != null) {
picstr = readFromSmb(smbMachine + record.get("gateIP") + "/" + picpath);
} else {
String[] ip = shareIP.split(",");
picstr = readFromSmb(smbMachine + ip[0] + "/" + picpath);
}
} else if (IPS_AND_SHARE.equals(picType)) {
// 多个IP模式 IP列表 + 共享文件模式 注意 必须 配置 shareIP才有用 ;
if (shareIP != null) {
String[] ip = shareIP.split(",");
for (int j = 0; j < ip.length; j++) {
picstr = readFromSmb(smbMachine + ip[j].trim() + "/" + picpath);
}
}
} else if (IP_AND_FTP.equals(picType)) {
// TODO please edit logic code
// IP + FTP模式
// Object gateIP = record != null ? record.get("gateIP") : null;
// if (Utils.isNotEmpty(gateIP)) {
// }
} else if (FTP.equals(picType)) {
// IP列表 + FTP模式 注意 必须 配置 ftpadd ftp.host才有用
picpath = picpath.replaceAll("[A-Za-z]:/", "").replaceAll("/", "\\\\");
byte[] image = ftpClient.retrieveFileStream(URLDecoder.decode(picpath, "utf-8"));
picstr = getImageStrByte(image);
} else {
}
}
if (picstr.equals(defaultImageStr())) {
picstr = "";
}
}
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
} finally {
}
return picstr;
}
public static void main(String[] args) {
// String str = GetHttpImageStr("file:Desktop-i9adh1c/123/1.jpg");
// System.out.println(str);
// base64StringToImage(str, "F:/123/12.jpg", "jpg");
// FileInputStream fis = new
// // FileInputStream("\\\\192.168.1.1\\share\\filename.xml");
// String[] ip = shareIP.split(",");
// String picstr = "";
// String picpath = "b:/150113/GOut_00FDF97627_144904.jpg";
// String pattern = "[A-Za-z]:/";
// Pattern p = Pattern.compile(pattern);
// Matcher m = p.matcher(picpath);
// picpath = picpath.replaceAll("[A-Za-z]:/", "").replaceAll("/", "\\\\");
// System.out.println(picpath);
// // for (int j = 0; j < ip.length; j++) {
// // picstr = Picture2Base64.readFromSmb("smb://"
// // + ip[j] + "/"
// // + picpath.substring(2, picpath.length()));
// // }
// //
// System.out.println(picstr);
// String str = GetImageStr("Z:/1.jpg");
// System.out.println(str);
// String a = "E:/150113/GOut_00B0415187_145934.jpg";
// System.out.println(a.substring(2,a.length()));
// String smbMachine = "smb://192.168.68.125/151213/1.jpg";
// String file = readFromSmb(smbMachine);
// System.out.println(file);
// String s = ConfigInitialization.get("shareIP");
// System.out.println(s);
String[] ipArr = "127.0.0.1,192.168.68.138,192.168.68.51".split(","); // 共享ip地址列表
String path = "/share/11.jpg";
for (int i = 0; i < ipArr.length; i++) {
try {
SmbFile smbFile = new SmbFile("smb://" + ipArr[i] + "/" + path); // 获取连接
smbFile.exists();
int length = smbFile.getContentLength();
if (length == 0) {
continue;
}
byte buffer[] = new byte[length];
SmbFileInputStream in = new SmbFileInputStream(smbFile);
// 建立smb文件输入流
while ((in.read(buffer)) != -1) {
System.out.println(Base64Util.encode(buffer));
}
in.close();
break;
} catch (IOException e) {
break;
}
}
}
}
图片转BASE64(带FTP读取)
最新推荐文章于 2023-09-01 16:00:05 发布