JavaのWebアプリケーション開発フレームワークによる、Webサイト開発の顛末記です。

EclipseのMavenを使った、Spring-MVC、Thymeleaf、MyBatis 等のプログラミングテクニックを、
備忘録的に記録しています。実際に動くソースコードを多用して説明していますので、
これからEclipseや、Spring-MVCを始めたいと思っている人にとって、少しでも参考になれば幸いです。
Spring-MVCの散歩道 > 応用の森(HTML編) > Base64形式の画像データ(jpeg/gif/png)を表示する方法

package jp.dip.arimodoki.cntl;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.commons.codec.binary.Base64;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import jp.dip.arimodoki.common.CConst;

@Scope("prototype")
@Controller
public class Base64Conv implements CConst {

    /**
     * Base64投入画面変換画面
     */
    @RequestMapping(value = "/base64input")
     public String base64input() throws Exception {
        return "base64";
    }

    /**
     * Base64変換実行
     */
    @RequestMapping(value = "/base64convert")
     public String base64convert(
             @RequestParam MultipartFile uploadfile,	//アップロードファイル
             Model model
         ) throws Exception {

        StringBuffer data = new StringBuffer();

        //submitされた画像データストリームを取得する
        InputStream is = uploadfile.getInputStream();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] indata = new byte[10240*16];
        int siz;
        //バイト配列に変換
        while( ( siz = is.read(indata, 0, indata.length) ) > 0 ) {
            os.write( indata, 0, siz );
        }
        //画像データをbase64エンコードする
        String base64 = new String(Base64.encodeBase64(os.toByteArray()), "ASCII");

        //画像タイプはJPEG固定
        data.append("data:image/jpeg;base64,");
        data.append(base64);

        //エンコードデータを、データモデルにセット(view の <img src= プロパティに反映)
        model.addAttribute("base64data", data.toString());

        return "base64";
    }
}