How to write A base64 encoded image with mimetype in Rails

Posted by : on

Category : Rails

Hello There, We often need to convert a base64 encoded image to actual image file. It generally happens When we work with apis. Here is an example how can we make a image from base64 encoded string with the actual MIMETYPE.

Write a method

Write a method say convert and write a set of lines into it.

def convert(base64_string)
# make sure you are passing base64 encoded string with MIMETYPE like 'data:image/jpeg;base64, some_string'
_image_with_mime_type = base64_string.match(/\Adata:([-\w]+\/[-\w\+\.]+)?;base64,(.*)/) || [] 
extension = MIME::Types[_image_with_mime_type[1]].first.preferred_extension
_image_data = _image_with_mime_type[2]
# Write image into a file
image_file = File.join(SOME_LOCATION, "#{FILE_NAME}.#{extension}")
# Like image_file = File.join(Rails.root, 'tmp', "#{ SecureRandom.uuid}.#{extension}")
File.open(image_file , "wb") do |file|
file.write(Base64.decode64(_image_data))
 end
end

# Call convert method
convert(BASE64_ENCODED_STRING_WITH_MIMETYPE)

Now you can see there is an image at specifiled location.

  • Note : You need to pass base64 encoded image string into method with the MIMETYPE, This method will break otherwise to fetch extension. Thanks!!


About Ram Laxman Yadav
Ram Laxman Yadav

Senior Software Engineering Professional | Tech Enthusiast | Mentor | Payments | Hospitality | E-Commerce, based in NCR, India

Email : info@ramlaxman.co.in

Website : https://ramlaxman.co.in