Summary
Base64エンコーダで画像ファイルを文字列、デコーダで文字列をImageIconに変換します。
Screenshot

Advertisement
Source Code Examples
JButton encode = new JButton("encode");
encode.addActionListener(e -> {
JFileChooser chooser = new JFileChooser();
chooser.addChoosableFileFilter(
new FileNameExtensionFilter("PNG (*.png)", "png"));
int retvalue = chooser.showOpenDialog(encode);
if (retvalue == JFileChooser.APPROVE_OPTION) {
Path path = chooser.getSelectedFile().toPath();
try {
textArea.setText(
Base64.getEncoder().encodeToString(Files.readAllBytes(path)));
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
JButton decode = new JButton("decode");
decode.addActionListener(e -> {
String b64 = textArea.getText();
if (b64.isEmpty()) {
return;
}
// byte[] bytes = b64.getBytes(StandardCharsets.ISO_8859_1);
// try (InputStream input = new ByteArrayInputStream(
// Base64.getDecoder().decode(bytes))) {
try (InputStream input = new ByteArrayInputStream(Base64.getDecoder().decode(b64))) {
label.setIcon(new ImageIcon(ImageIO.read(input)));
} catch (IOException ex) {
ex.printStackTrace();
}
});
View in GitHub: Java, KotlinDescription
上記のサンプルでは、JDK 1.8.0から導入されたBase64クラスを使用して、画像ファイルのBase64形式文字列へのエンコードやBase64形式文字列からbyte配列へのデコードを行っています。
encodeJFileChooserで選択した画像ファイルをBase64.EncoderのencodeToString(...)メソッドで文字列に変換してJTextAreaに設定- ファイルの
byte[]への変換にはFiles.readAllBytes(...)メソッドを使用
decodeJTextAreaから取得した文字列をBase64.Decoderのdecode(String)メソッドでbyte配列に変換、さらにnew ImageIcon(ImageIO.read(new ByteArrayInputStream(byte[])))でImageIconに変換してJLabelに設定decode(src)はdecode(src.getBytes(StandardCharsets.ISO_8859_1))と同等
Reference
- Base64 (Java Platform SE 8)
- java - JEditorPane Content Type for HTML Embedded Base64 Images - Stack Overflow
<img src='data:image/png;base64,iVBOR...' />のようにHTMLテキスト中に埋め込まれたBase64文字列をJEditorPane(HTMLEditorKit)で画像として表示するサンプルが回答されている