2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pillowで読み込んだ画像をS3にアップロードする

Posted at

以下の関数を実行すればOKです.

def upload_image_to_s3(img, bucket_name, key_name):
    """
    imgはPillowのImageオブジェクト
    """
    conn = S3Connection(AWS_ACCESS_ID, AWS_SECRET_KEY)
    bucket = conn.get_bucket(bucket_name)
    k = Key(bucket, key_name)
    image_buffer = io.BytesIO()
    img.save(image_buffer, 'JPEG')
    image_buffer.seek(0)  # これを忘れると空データがs3に送られる
    k.set_contents_from_string(image_buffer.read())

ポイント: image_buffer.seek(0)を忘れない

seek(0)の存在を忘れており,1時間もハマってしまいました.
PillowのImageでsaveメソッドを使った時,ファイルのカーソル?がファイルの末尾に来るらしく,カーソルを最初に戻してあげる必要があるみたいですね.忘れると,いきなりEOF,つまり終わりということでS3に空っぽの画像ファイルがアップロードされました.

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?