5

base64 でエンコードされた画像をデコードし、ReportLab を使用して生成した PDF に入れようとしています。私は現在、そのようにしています(image_database64でエンコードされた画像で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 とは異なる画像を読み取ることは知っていますが、名前付きの一時ファイルの作成を回避し、ディスクにファイルを書き込まずに、ファイルのようなオブジェクトのみでこれを行う方法はありますか?

4

4 に答える 4

2

StringIO()をでラップする必要がPIL.Image.openあるので、単純にimg_size = ImageReader(PIL.Image.open(img_file)).getSize()。Tommasoの回答が示唆しているように、実際にはImage.sizeの周りに薄いラッパーがあります。boundまた、実際には、reportlab.Imageのモードでdescサイズを自分で計算する必要はありません。

img_height = 1.5 * inch  # max image height
img_file = StringIO.StringIO(image_data.decode('base64'))
img_file.seek(0)
img = Image(PIL.Image.open(img_file),
            width=float('inf'),
            height=img_height,
            kind='bound')
)
story.append(img)
于 2012-04-03T07:09:00.133 に答える
0

画像はすでに JPEG であるため、このコードは PIL なしで機能します。 raw は base64 文字列を辞書から取り出すだけです。デコードされた「文字列」を StringIO でラップするだけです。

        raw = element['photographs'][0]['jpeg']
        photo = base64.b64decode(raw)
        c.drawImage(ImageReader(StringIO.StringIO(photo)), 0.5*inch, self.y, height = self.PHOTOHEIGHT, preserveAspectRatio = True)
于 2012-11-19T17:36:49.930 に答える
0

ReportLab には詳しくありませんが、PIL を直接使用できる場合は次のように動作します。

...
img = Image.open(img_file)
width, height = img.size
...

PIL Imageクラスの参照については、こちらをご覧ください

于 2012-04-02T22:17:40.743 に答える