Rails Active Storage + AWS Rekognition:如何获取IO文件

时间:2019-03-11 10:07:21

标签: ruby-on-rails amazon-rekognition

我正在尝试将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中?

1 个答案:

答案 0 :(得分:1)

有两种方法可以将图像传递到Aws::Rekognition

  1. AWS S3图像URL和名称
resp = rekognition.detect_faces(
        {image:
          {s3_object:
            {bucket: `bucket name`,
              name: `pull path of file`,
            },
          }, attributes: ['ALL'],
        }
      )
  1. 通过图片对象
rekognition.detect_faces({
         image: { bytes: File.read(`path of file`) }
       })

在您的情况下,您正在传递ActiveStorage对象,而该对象无法被AWS解​​析。这就是为什么它会引发错误。