如何将 Base64 图像附加到 Active Storage 对象?
How to attach Base64 image to Active Storage object?
我可以从光盘附加一个 png 图像,一切正常:
obj.attachment.attach(
io: File.open('dog.png'),
filename: "image_name",
content_type: "image/png"
)
但是当我保存一个编码为 String
类似 "data:image/png;base64,iVB**..REST OF DATA..**kSuQmCC"
的 Base64 png 图像时,它无法给出像太小的空方块这样的结果,作者:
obj.attachment.attach(
io: StringIO.new(encoded_base_sixty_four_img),
filename: "image_name",
content_type: "image/png"
)
我也尝试解码它,但给出了同样的错误:
decoded_base_sixty_four_img = Base64.decode64(encoded_base_sixty_four_img)
obj.attachment.attach(
io: StringIO.new(decoded_base_sixty_four_img),
filename: "image_name",
content_type: "image/png"
)
还尝试将此解码值写入 File
但没有任何效果也给出空白图像结果:
file = file.write(decoded_base_sixty_four_img)
obj.attachment.attach(
io: file,
filename: "image_name",
content_type: "image/png"
)
还有其他想法吗?
感谢@tadman,data:image/png;base64,
部分无法由 Base64.decode64
处理,当我将其剥离时一切正常。
这对我有用。
Model.create!(
product: product,
image: {
io: StringIO.new(Base64.decode64(params[:base_64_image].split(',')[1])),
content_type: 'image/jpeg',
filename: 'image.jpeg'
}
)
我可以从光盘附加一个 png 图像,一切正常:
obj.attachment.attach(
io: File.open('dog.png'),
filename: "image_name",
content_type: "image/png"
)
但是当我保存一个编码为 String
类似 "data:image/png;base64,iVB**..REST OF DATA..**kSuQmCC"
的 Base64 png 图像时,它无法给出像太小的空方块这样的结果,作者:
obj.attachment.attach(
io: StringIO.new(encoded_base_sixty_four_img),
filename: "image_name",
content_type: "image/png"
)
我也尝试解码它,但给出了同样的错误:
decoded_base_sixty_four_img = Base64.decode64(encoded_base_sixty_four_img)
obj.attachment.attach(
io: StringIO.new(decoded_base_sixty_four_img),
filename: "image_name",
content_type: "image/png"
)
还尝试将此解码值写入 File
但没有任何效果也给出空白图像结果:
file = file.write(decoded_base_sixty_four_img)
obj.attachment.attach(
io: file,
filename: "image_name",
content_type: "image/png"
)
还有其他想法吗?
感谢@tadman,data:image/png;base64,
部分无法由 Base64.decode64
处理,当我将其剥离时一切正常。
这对我有用。
Model.create!(
product: product,
image: {
io: StringIO.new(Base64.decode64(params[:base_64_image].split(',')[1])),
content_type: 'image/jpeg',
filename: 'image.jpeg'
}
)