How to decode a base64 image file using a mini mage in Rails?

In our Rails 4, the image is uploaded to the server in the base64 line:

uploaded_io = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2....." 

We would like to get type, size, etc. and save the file as an image file in the file system. Our application has a gem 'mini_magick' . Is there a way to handle a base64 image string using mini_magick ?

+5
source share
1 answer

Yes, there is a way to do this.

Reset the metadata "data:image/jpeg;base64," from the input line and then decode it using the Base64.decode64 method. You will get a binary blob. Direct this blob to MiniMagick::Image.read . ImageMagick is smart enough to guess all the metadata for you. Then process the image using the mini_magick methods, as usual.

 require 'base64' uploaded_io = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2....." metadata = "data:image/jpeg;base64," base64_string = uploaded_io[metadata.size..-1] blob = Base64.decode64(base64_string) image = MiniMagick::Image.read(blob) image.write 'image.jpeg' # Retrieve attributes image.type # "JPEG" image.mime_type # "image/jpeg" image.size # 458763 image.width # 640 image.height # 480 image.dimensions # [640, 480] # Save in other format image.format 'png' image.write 'image.png' 
+12
source

Source: https://habr.com/ru/post/1236017/


All Articles