Skip to content

Instantly share code, notes, and snippets.

@salahuddin-rakib
Last active August 13, 2022 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salahuddin-rakib/95cd008ee414bedf8b2f8af48b47d947 to your computer and use it in GitHub Desktop.
Save salahuddin-rakib/95cd008ee414bedf8b2f8af48b47d947 to your computer and use it in GitHub Desktop.
It shows how we can convert base64 text to an image file.
module Base64ToImageFile
extend ActiveSupport::Concern
def convert_base64_to_image_file(base64_data, filename = 'image')
return base64_data unless base64_data.present? && base64_data.is_a?(String)
regex = /data:image\/([a-z]{3,4});base64,/
type_fetch_regex = /\/(.*?);/
start_text = regex.match(base64_data)
type = base64_data[type_fetch_regex, 1]
if start_text && type
file = File.new("#{filename}.#{type}", 'wb')
file.write(Base64.decode64(base64_data[start_text.to_s.length..-1]))
file # returns crated file.
else
# base64_data => if you want to return the passing value
nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment