Last active
April 29, 2024 05:58
-
-
Save hateradio/3c2cae39d432dfbe4647 to your computer and use it in GitHub Desktop.
ruby image to base64 string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you! just what i needed