gpt4 book ai didi

ruby-on-rails - 有没有办法将二进制数据转换为允许 ActiveStorage 将其作为图像附加到我的用户模型的数据类型

转载 作者:行者123 更新时间:2023-12-03 16:20:15 24 4
gpt4 key购买 nike

我正在点击一个 api 来获取他们存储的图像并将其用作我们应用程序用户的个人资料图片。我将 Ruby on Rails 和 ActiveStorage 与 AWS 结合使用来附加和存储图像。他们发回的内容是这样的:

{"status"=>"shared", "values"=>[{"$objectType"=>"BinaryData", "data"=>"/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAAT.....KK5tT/9k=", "mime_type"=>"image/jpeg", "metadata"=>{"cropped"=>false}}]}

我尝试了很多不同的方法来附加它并操作数据,例如按原样附加它,Base64.decode64,Base64.encode64。我还尝试创建一个新文件,然后附加它。这里有些例子:
data = Base64.decode64(Base64.encode64(response[:selfie_image]["values"][0]["data"]))

user.profile_pic.attach!(
io: StringIO.new(open(data).read),
filename: "#{user.first_name}_#{user.last_name}_#{user.id}.jpg",
content_type: "image/jpeg"
)
data = Base64.decode64(Base64.encode64(response[:selfie_image]["values"][0]["data"]))

out_file = File.new("#{user.first_name}_#{user.last_name}_# . {user.id}.jpg", "w")
out_file.puts(data)
out_file.close

user.profile_pic.attach(
io: StringIO.new(open(out_file).read),
filename: "#{user.first_name}_#{user.last_name}_#{user.id}.jpg",
content_type: "image/jpeg"
)

我也试过:
user.profile_pic.attach(out_file)

它要么说附件为零,要么根据我如何操作数据,它会说不是 jpeg 文件内容标题类型错误,并将其作为图像魔法错误抛出。

我如何操作这些数据以便能够将它作为图像附加给我们的用户使用 ActiveStorage?

最佳答案

为了让它工作,我必须添加 gem "mini_magick"到我的 gemfile,然后使用它来解码我从 api 调用接收的图像数据,然后将其转换为 blob,以便 ActiveStorage 可以处理它。

data = response[:selfie_image]["values"][0]["data"]
decoded_data = Base64.decode64(data)
image = MiniMagick::Image.read(decoded_data)
image.format("png")
user.profile_pic.attach(
io: StringIO.new(image.to_blob),
filename: "#{user.id}_#{user.first_name}_#{user.last_name}.png",
content_type: "image/jpeg"
)

关于ruby-on-rails - 有没有办法将二进制数据转换为允许 ActiveStorage 将其作为图像附加到我的用户模型的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55787737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com