How to decode base64 image file with mini_magick in Rails?

我们两清 提交于 2019-12-22 08:03:50

问题


In our Rails 4 app, the image is uploaded to server in a base64 string:

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

We would like to to retrieve the content type, size and so on and save the file as image file on file system. There is a gem 'mini_magick' in our app. Is there a way to process base64 image string with mini_magick?


回答1:


Yes, there is a way to do that.

Strip metadata "data:image/jpeg;base64," from your input string and then decode it with Base64.decode64 method. You'll get binary blob. Feed that blob to MiniMagick::Image.read. ImageMagick is smart enough to guess all metadata for you. Then process the image with 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'


来源:https://stackoverflow.com/questions/33728194/how-to-decode-base64-image-file-with-mini-magick-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!