You can decode raw bytes using one of the various ImageMagick libraries, and then ask ImageMagick for the format. For example, RMagick :
require 'rmagick' bytes = ActiveSupport::Base64.decode64(params[:image]) img = Magick::Image.from_blob(bytes).first fmt = img.format
This will give you 'PNG' , 'JPEG' , etc. in fmt . ImageMagick checks bytes for magic numbers and other identifying information, so it does not need a file name to find out which image you give it.
As for the file name, you're out of luck if someone clearly doesn't tell you what it is. A file name rarely matters, and you should never use a file name that you did not create to save anything; the user-provided file name should only be used to display the name for people, for your own file name (which you know is safe) if you need it.
source share