Skip to content

Commit 903a556

Browse files
author
Evan Lin
committed
fix: Correctly read image stream and reset pointer
1 parent 5d39772 commit 903a556

1 file changed

Lines changed: 11 additions & 5 deletions

File tree

main.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -132,18 +132,24 @@ async def handle_callback(request: Request):
132132
print(f"Received image from user: {user_id}")
133133

134134
message_content = await line_bot_api.get_message_content(event.message.id)
135-
image_content = b''
136-
async for s in message_content.iter_content():
137-
image_content += s
138-
img_stream = PIL.Image.open(BytesIO(image_content))
135+
136+
# Asynchronously read all content chunks into a byte string
137+
image_bytes = b''
138+
async for chunk in message_content.iter_content():
139+
image_bytes += chunk
140+
141+
# Create an in-memory binary stream from the bytes
142+
image_stream = BytesIO(image_bytes)
143+
# Reset the stream's pointer to the beginning for the upload function
144+
image_stream.seek(0)
139145

140146
file_name = f"{uuid.uuid4()}.jpg"
141147
gcs_uri = None
142148
response = "抱歉,處理您的圖片時發生錯誤。" # Default error message
143149

144150
try:
145151
gcs_uri = upload_to_gcs(
146-
img_stream, file_name, google_storage_bucket)
152+
image_stream, file_name, google_storage_bucket)
147153
if gcs_uri:
148154
print(f"Image uploaded to {gcs_uri}")
149155
response = generate_image_description(gcs_uri)

0 commit comments

Comments
 (0)