import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
public class ImageUtils {
public static void main(String[] args) {
String str = img2Binary("C:\\Users\\hny\\Desktop\\favicon.jpg");
System.out.println(str);
binary2Img("C:\\Users\\hny\\Desktop\\favicon2.jpg", str);
}
/**
* 图片转二进制字符串
*
* @param path 图片路径
* @return
*/
public static String img2Binary(String path) {
File file = new File(path);
if (!file.exists()) {
return null;
}
try {
BufferedImage bi = ImageIO.read(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String suffix = getSuffix(path);
ImageIO.write(bi, suffix, baos);
byte[] bytes = baos.toByteArray();
return new sun.misc.BASE64Encoder().encodeBuffer(bytes).trim();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 字符串转图片文件
*
* @param path 图片路径
* @param imgBinary 图片字符串
*/
public static void binary2Img(String path, String imgBinary) {
try {
File file = new File(path);
byte[] bytes1 = new sun.misc.BASE64Decoder().decodeBuffer(imgBinary);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 = ImageIO.read(bais);
String suffix = getSuffix(path);
ImageIO.write(bi1, suffix, file);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取图片后缀名
*
* @param path
* @return
*/
private static String getSuffix(String path) {
int index = path.contains(".") ? path.lastIndexOf(".") : -1;
if (index > -1) {
return path.substring(index + 1);
}
return null;
}
}