LoginSignup
3
5

More than 5 years have passed since last update.

クラスパス上にあるPNGファイルをBASE64形式で取得する

Last updated at Posted at 2016-01-17

きっかけ

HTMLないしはCSSなどからごく小さな画像ファイルをBASE64で受け取る、いわゆるdata URI schemeと呼ぶものに対して、作ることがあったのでメモを残します。

コード例

PictureDecodeService.java

import org.apache.commons.codec.binary.Base64;

public class PictureDecodeService {
    String loadBinaryImage(String filename) throws Exception {

        // ファイルインスタンスを取得し、ImageIOへ読み込ませる
        File f = new File(filename);
        BufferedImage image = ImageIO.read(f);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        image.flush();

        // 読み終わった画像をバイト出力へ。
        ImageIO.write(image, "png", bos);
        bos.flush();
        bos.close();
        byte[] bImage = baos.toByteArray();

        // バイト配列→BASE64へ変換する
        Base64 base64 = new Base64();
        byte[] encoded = base64.encode(bImage);
        String base64Image = new String(encoded);

        return base64Image;
    }
}

こうして生成したBASE64をdataURISchemeに渡せば完成です。

<img src="data:image/png;base64,(BASE64化した文字列)">

JSPを使うと、

<img src="data:image/png;base64,${base64Image}"> とかでも使えますね!


3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5