PIL で処理したデータをバイナリーに変換する方法です。
output = io.BytesIO()
img_pil.save(output, format='JPEG')
image_jpg = output.getvalue()
応用例として、PIL でリサイズしたイメージを、CouchDB に保存する方法です。
CouchDB のデータベースは、jpg です。
入力データは、A0001.jpg です。
resize_couchdb.py
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
# resize_couchdb.py
#
# Aug/04/2017
#
import sys
import io
import requests
#
from PIL import Image
# --------------------------------------------------------------------
def image_resize_proc(image_pil):
width, height = image_pil.size
print(width, height)
width_new = int(width / 2 + 0.5)
height_new = int(height / 2 + 0.5)
resize_img = image_pil.resize((width_new, height_new))
width, height = resize_img.size
print(width, height)
#
return resize_img
# --------------------------------------------------------------------
# [4]:
def to_couchdb_proc(url_jpg_file,image_jpg):
#
headers = {'Content-type': 'image/jpeg'}
try:
rr=requests.put(url_jpg_file,data=image_jpg,headers=headers)
print(rr)
print(str(rr.content,'utf-8'))
print()
print(rr.headers)
except Exception as ee:
sys.stderr.write(str(ee) + "\n")
#
# --------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
#
jpg_in = "A0001.jpg"
array_a = jpg_in.split(".")
key = array_a[0]
sys.stderr.write("key = " + key + "\n")
#
img_pil = Image.open(jpg_in)
#
img_pil = image_resize_proc(img_pil)
#
output = io.BytesIO()
img_pil.save(output, format='JPEG')
image_jpg = output.getvalue()
#
url="http://localhost:5984"
url_jpg_file = url + "/jpg/" + key + "/" + jpg_in
#
to_couchdb_proc(url_jpg_file,image_jpg)
#
sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------
CouchDB にデータが保存されたことを確認
$ curl -X GET --noproxy localhost http://localhost:5984/jpg/_all_docs
{"total_rows":1,"offset":0,"rows":[
{"id":"A0001","key":"A0001","value":{"rev":"1-ac131d333b4c4ad99659cda53310843d"}}
]}