LoginSignup
1
1

More than 3 years have passed since last update.

base64 画面に画像を表示させる

Posted at

javaでDBに保存されている画像情報から画面(html)上に画像を表示させる方法をよく忘れるのでメモとして。

データベース情報

スクリーンショット 2020-12-27 203555.png

ファイル名:サンプル画像
ファイルパス:画像の保存されているパス
上記のテーブルのような構成

 ロジック

public imageDto getImage(String id) throws Exception {
         // DBから情報を取得する   
         List<TProductImg> imgList = imgRepository.findByid(Long.parseLong(id));
        if (!ObjectUtils.isEmpty(imgList)) {
            List<String> dispImgPath = new ArrayList<>();
            for (TProductImg e : imgList) {
                StringBuffer data = new StringBuffer();
                data.append("data:image/jpeg;base64,");
                productDto.setFilename(e.getFilename());
                // 取得した画像情報をエンコード化      
                String base64 = new String(Base64.encodeBase64(Files.readAllBytes(Paths.get(e.getFilepath()))), "ASCII");
                data.append(base64);
                dispImgPath.add(data.toString());
            }
            imageDto.setDispImgPath(dispImgPath);
        }
    }

最後にエンコード化されたdispImgPathを画面(html)で表示させる。

1
1
2

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
1
1