LoginSignup
0
0

More than 1 year has passed since last update.

画像を読み込み、byteArrayで遊び理解を深めるコード

Last updated at Posted at 2023-04-25

やること

画像データをリクエストボディに詰めたりのテストをpythonで実施するための型理解
byteArrayとbytes型、_io.BytesIO型の違いを見て確かめる

記事の活かし方

下のコードをコピペして、自分の画像(パス)で検証を行う。
そして他に気になる点をprintなどして調査して知識を深める

画像を読み込み、byteArrayで遊び理解を深めるコード

testByteArray.py
import matplotlib.pyplot as plt
from PIL import Image
import io 

filename = 'images/testImage.jpg'

# Read image into memory
payload = None
with open(filename, 'rb') as f:
    payload = f.read()

print("payload is")
print(type(payload)) # <class 'bytes'>
print(payload[:100]) # b'\xff\xd8\xff\xe1\x02〜〜〜〜

testBody=bytearray(payload)

print("testBody is")
print(type(testBody)) # <class 'bytearray'>
print(testBody[:100]) # bytearray(b'\xff\xd8\xff\xe1\x02〜〜〜〜

img_bin = io.BytesIO(payload) # ここはpayloadでもtestBodyでも問題なく動く
print("img_bin is")
print(img_bin) # メモリ格納先が表示される <_io.BytesIO object at 0x10d68d760>
print(type(img_bin)) # <class '_io.BytesIO'>
# print(img_bin[:100]) _io.BytesIO' object is not subscriptable
img = Image.open(img_bin)
plt.imshow(img)
img.save("testOutPut.png","PNG") # 問題なく表示される
0
0
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
0
0