如何在Rails中使用mini_magick解码base64图像文件? [英] How to decode base64 image file with mini_magick in Rails?
问题描述
在我们的Rails 4应用程序中,图像以base64字符串上传到服务器:
In our Rails 4 app, the image is uploaded to server in a base64 string:
uploaded_io = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2....."
我们想要检索内容类型,大小等,并将文件保存为文件系统上的图像文件。我们的应用程序中有一个 gem'mini_magick'
。有没有办法用 mini_magick
处理base64图像字符串?
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
?
推荐答案
是的,有办法做到这一点。
Yes, there is a way to do that.
从输入字符串中剥离元数据data:image / jpeg; base64,
然后用<解码 Base64.decode64
方法。你会得到二进制blob。将blob提供给 MiniMagick :: Image.read
。 ImageMagick非常聪明,可以为您猜测所有元数据。然后像往常一样使用 mini_magick
方法处理图像。
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'
这篇关于如何在Rails中使用mini_magick解码base64图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!