LoginSignup
4

More than 5 years have passed since last update.

posted at

updated at

Base64でエンコードされている文字列を画像ファイルに変換する

諸事情でbase64でエンコードさえている画像が沢山保存されているブラウザのキャッシュから実画像ファイルを抽出する必要があった。base64の文字列をインスペクターで抽出して、以下のスクリプトにコピペして実行すると画像を抽出できる。

単に画像の形式の宣言部分を端折ってbase64の文字列部分だけをライブラリでデコードすれば良い。
拡張子は合わせる必要がある。

require 'base64'
str='data:image/jpeg;base64,...' # コピペする
File.open("%04d.jpg" % i, 'wb') do|f|
    f.write(Base64.decode64(str['data:image/jpeg;base64,'.length .. -1]))
end

一つのファイルに何行もある場合は以下のようにした。

require 'base64'
i = 0
File.foreach('photos.base64') do |str|
  puts str.size
  i+=1
  File.open("%04d.jpg" % i, 'wb') do|f|
    f.write(Base64.decode64(str['data:image/jpeg;base64,'.length .. -1]))
  end
end

サクッと変換できた。

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
What you can do with signing up
4