Last active
August 13, 2022 09:21
-
-
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.
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
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