Skip to content

Instantly share code, notes, and snippets.

@hateradio
Last active April 29, 2024 05:58
Show Gist options
  • Save hateradio/3c2cae39d432dfbe4647 to your computer and use it in GitHub Desktop.
Save hateradio/3c2cae39d432dfbe4647 to your computer and use it in GitHub Desktop.
ruby image to base64 string
require 'base64'
# converts attached PNGs into base64 strings
# Eg
# <img src="my.png" /> to <img src="data:image/png;base64,..." />
class To64Html
def initialize(path)
@path = path
end
def self.img64(path)
File.open(path, 'rb') do |img|
'data:image/png;base64,' + Base64.strict_encode64(img.read)
end
end
def html(name='based64.html')
File.open(@path, 'r') do |h|
html = h.read.gsub(/src="(.*\.png)"/) do |g|
"src='#{To64Html::img64($1)}'"
end
IO.write(name, html)
p 'done'
end
end
end
# Single PNG to base64 string
# p To64Html::img64('r_files/c264ce0e71c20d0eb31686641f83deda.png')
if ARGV.length > 0
To64Html.new(ARGV[0]).html()
end
@tsboh
Copy link

tsboh commented Oct 16, 2019

Thank you! just what i needed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment