ruby-on-rails - Rails Active Storage + AWS Rekognition:如何获取 IO 文件
问题描述
我正在尝试将 AWS Rekognition 集成到我的 Rails 应用程序中。用户通过 Active Storage 上传他的头像后,Rekognition 应该显示一些关于它的信息。
def update
respond_to do |format|
if @user.update(user_params)
if @user.images.attached?
Aws.config.update({
region: 'us-west-2',
credentials: Aws::Credentials.new('ACCESS_KEY', 'SECRET_KEY')
})
rekognition = Aws::Rekognition::Client.new(region: Aws.config[:region], credentials: Aws.config[:credentials])
img = @user.images.first. # original was: File.read(ARGV.first)
#detect faces
resp = rekognition.detect_faces({
image: { bytes: img },
attributes: ["ALL"], # What attributes to return
})
resp.face_details[0].emotions.each do |emo|
puts emo.type + " " + emo.confidence.to_i.to_s #=> Strings "HAPPY", "SAD", "ANGRY"
end
end
end
end
但是,我得到了错误
expected params[:image][:bytes] to be a String or IO object, got value #<ActiveStorage::Attachment id: 4, name: "images", record_type: "User", record_id: 47, blob_id: 9, created_at: ""> (class: ActiveStorage::Attachment) instead.
如何将图像文件属性导入 AWS Rekognition?
解决方案
有两种方法可以将图像传递给Aws::Rekognition
.
- AWS S3 图像 URL 和名称
resp = rekognition.detect_faces( {image: {s3_object: {bucket: `bucket name`, name: `pull path of file`, }, }, attributes: ['ALL'], } )
- 通过图像对象
rekognition.detect_faces({ image: { bytes: File.read(`path of file`) } })
在您的情况下,您正在传递ActiveStorage
AWS 无法解析的对象。这就是它抛出错误的原因。
推荐阅读
- sql - 日期之间的频率
- python - MySQL 查询在 Django 上没有提供足够的参数错误
- image - Xamarin Forms 选择多个图像,取消并重新排列
- visual-studio-code - 如何更改 vscode-server 目录
- javascript - 比较 2 个对象数组并找到匹配的颜色 ID,然后创建一个新数组 Javascript
- android - Unity 5.6.7 - UnityWebRequest SSL/HTTPS
- algorithm - 给定一个数字 k 和一个图表是否有一个 DFS 运行将使森林大于 k
- r - 如何在 R 代码中的两级标题上旋转数据框
- c# - 如何在后台进程中拥有 HttpContext
- flutter - 如何禁用按钮自身颤动