Image display
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);
}
Image converted to base64 string
public static String GetImageStr() {
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();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
Convert base64 string to image
public static boolean GenerateImage(String imgStr) {
if (imgStr == null)
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
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[] to base64
BASE64Encoder base64Encoder = new BASE64Encoder();
String encode = base64Encoder.encode(str.getBytes());
System.out.println("转base64后:" + encode);
Base64 to byte[]
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] decodeBuffer = base64Decoder.decodeBuffer(str);
System.out.println("base64转回:" + new String(decodeBuffer));