Skip to content

Instantly share code, notes, and snippets.

@holysugar
Created March 10, 2011 09:53
Show Gist options
  • Save holysugar/863841 to your computer and use it in GitHub Desktop.
Save holysugar/863841 to your computer and use it in GitHub Desktop.
convert resource url in a html file to data scheme uri
require 'open-uri'
require 'image_size'
class ConvertAssetInline
def initialize
@orig = nil
@cache = {}
end
def convert(url)
body = crawl(url)
convert_img(body, url)
convert_favicon(body, url)
body
end
private
def crawl(url, options = {})
open(url) {|f| f.read }
end
def url_to_data(url, base_url = nil, content_type = nil)
url = URI.join(base_url, url) if base_url
url = url.to_s
return @cache[url] if @cache[url]
target = open(url) {|f| f.read }.freeze
unless content_type
target_is = ImageSize.new(target)
content_type = "image/#{target_is.get_type.downcase}"
end
result = datascheme(target, content_type)
@cache[url] = result
result
end
def datascheme(binary, content_type)
target_b64 = [binary].pack('m')
"data:#{content_type};base64,#{target_b64}"
end
def convert_img(body, base_url)
body.gsub!(/<img[^>]*?src=["'](.*?)["']/) { # don't care there are ["'] in the URL
$&.sub($1, url_to_data($1, base_url))
}
end
def convert_favicon(body, base_url)
body.gsub!(/<link [^>]*rel="shortcut icon".*?>/) {|matched|
matched.sub(/href=["'](.*?)["']/) {
$&.sub($1, url_to_data($1, base_url, 'image/vnd.microsoft.icon'))
}
}
end
# def convert_stylesheets ...
end
c = ConvertAssetInline.new
puts c.convert ARGV.first
@holysugar
Copy link
Author

fixme :)

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