Created
October 1, 2021 17:20
-
-
Save Snarp/1c6df18e76504f7fbd0f65a4677919bd to your computer and use it in GitHub Desktop.
Embed raster image file (JPG, PNG, GIF, BMP) in SVG file
This file contains hidden or 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' | |
require 'fastimage' | |
# This is not raster-to-vector conversion; this is putting a raster in a vector | |
# suit. If you find yourself in need of this information, something is very | |
# wrong. Something is very wrong. | |
def embed_raster_image_in_svg(input_image ="raster.jpg", | |
output_image="raster_in_vector.svg") | |
dimensions = FastImage::size(input_image) | |
width = dimensions[0] | |
height = dimensions[1] | |
mime_type = case File.extname(input_image).downcase | |
when ".jpg", ".jpeg" | |
"image/jpeg" | |
when ".gif" | |
"image/gif" | |
when ".png" | |
"image/png" | |
when ".bmp" | |
"image/bmp" | |
else | |
raise | |
end | |
data = Base64::encode64 File.binread(input_image) | |
data = %{ | |
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> | |
<image id="embedded-raster" width="#{width}" height="#{height}" xlink:href="data:#{mime_type};base64,#{data}" /> | |
</svg> | |
}.strip | |
File.write(output_image, data) | |
return data | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment