base64 でエンコードされた画像をデコードし、ReportLab を使用して生成した PDF に入れようとしています。私は現在、そのようにしています(image_data
base64でエンコードされた画像でstory
あり、すでにReportLabの話です):
# There is some "story" I append every element
img_height = 1.5 * inch # max image height
img_file = tempfile.NamedTemporaryFile(mode='wb', suffix='.png')
img_file.seek(0)
img_file.write(image_data.decode('base64'))
img_file.seek(0)
img_size = ImageReader(img_file.name).getSize()
img_ratio = img_size[0] / float(img_size[1])
img = Image(img_file.name,
width=img_ratio * img_height,
height=img_height,
)
story.append(img)
そしてそれは機能します(それでも私には醜く見えますが)。一時ファイルを取り除くことを考えました (ファイルのようなオブジェクトでうまくいくのではないでしょうか?)。
モジュールを使用しようとした一時ファイルを取り除くために、StringIO
ファイルのようなオブジェクトを作成し、ファイル名の代わりにそれを渡します。
# There is some "story" I append every element
img_height = 1.5 * inch # max image height
img_file = StringIO.StringIO()
img_file.seek(0)
img_file.write(image_data.decode('base64'))
img_file.seek(0)
img_size = ImageReader(img_file).getSize()
img_ratio = img_size[0] / float(img_size[1])
img = Image(img_file,
width=img_ratio * img_height,
height=img_height,
)
story.append(img)
しかし、これにより、次のメッセージでIOErrorが表示されます:「画像ファイルを識別できません」。
ReportLab が PIL を使用して jpg とは異なる画像を読み取ることは知っていますが、名前付きの一時ファイルの作成を回避し、ディスクにファイルを書き込まずに、ファイルのようなオブジェクトのみでこれを行う方法はありますか?