How to write A base64 encoded image with mimetype in Rails | Ram Laxman Yadav

How to write A base64 encoded image with mimetype in 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}") , "wb") do |file|

# Call convert method


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!!
Ram Laxman Yadav
Ram Laxman Yadav
Ruby on Rails Developer