图片显示
/**
* 图片显示
*
* @throws IOException
*/
public static void photoShow() throws IOException {
File file = new File("D:\\Java\\IdeaProjects\\acs\\RE4Ik0b_1920x1080.jpg");
BufferedImage bufferedImage = ImageIO.read(file);
ImageIcon imageIcon = new ImageIcon(bufferedImage);
JFrame jFrame = new JFrame();
jFrame.setLayout(new FlowLayout());
jFrame.setSize(500, 500);
JLabel jLabel = new JLabel();
jLabel.setIcon(imageIcon);
jFrame.add(jLabel);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
图片转化成base64字符串
/**
* 图片转化成base64字符串
*
* @return
*/
public static String GetImageStr() {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
String imgFile = "D:\\Java\\IdeaProjects\\acs\\RE4Ik0b_1920x1080.jpg";//待处理的图片
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try {
in = Files.newInputStream(Paths.get(imgFile));
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
//对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);//返回Base64编码过的字节数组字符串
}
base64字符串转化成图片
/**
* base64字符串转化成图片
*
* @param imgStr base64字符串
* @return
*/
public static boolean GenerateImage(String imgStr) { //对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) //图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {//调整异常数据
b[i] += 256;
}
}
//生成jpeg图片
String imgFilePath = "D:\\Java\\IdeaProjects\\acs\\RE4Ik0b_1920x10802.jpg";//新生成的图片
OutputStream out = Files.newOutputStream(Paths.get(imgFilePath));
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
byte[]转base64
BASE64Encoder base64Encoder = new BASE64Encoder();
String encode = base64Encoder.encode(str.getBytes());
System.out.println("转base64后:" + encode);
Base64转byte[]
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] decodeBuffer = base64Decoder.decodeBuffer(str);
System.out.println("base64转回:" + new String(decodeBuffer));
版权声明:本文为weixin_45265547原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。