5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

sinatra+erbでDBに格納しているバイナリ画像を表示する方法

Last updated at Posted at 2013-10-30

Google先生にお願いしても探しきれなかったので、PHPの方法を真似る。
他に方法があるのかもしれないけど自分の使用方法ではこれで問題なし。
MySQL使ってます、念の為。

require 'base64'
 
def convert_image_source(i)
  base64 = Base64.encode64(i).gsub(/\n/, "") +  "\n"
  mime = "image/jpg"
  return "data:"+ mime + ";base64," + base64
end
 
@indata = convert_image_source(result)

resultにはバイナリが格納されていると仮定する。
なぜか改行コードが混じっていたのでgsub(/\n/,"")+ "\n"しているけどDBへの書き込みでヘタこいてる可能性が高いな。

erbで読み込む例

<img src=<%= @indata %>WIDTH=40 HEIGHT=40>
5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?