2017-04-04 5 views
0

メモリ内のファイルライクなオブジェクトがファイルのように動作すると想定します。私は、ディスクにJPEGファイルを保存して、通常の過程で読み取る場合、プログラムは正常に動作しますが、TextractがTextractはJpegImageFile(StringIOオブジェクト)を読み取ることができません

<StringIO.StringIO instance at 0x05039EB8> 

を「読み」を取得することはできませんよ。

jpegファイルは、Ned Batchelderの優れたブログExtracting JPGs from PDFsに基づいてpdfsから抽出されています。以下の関連コード:

type(jpg) --> str (on 2.7) 
buff = StringIO.StringIO() 
buff.write(jpg) 
buff.seek(0) 
type(buff) --> instance 
print buff --><StringIO.StringIO instance at 0x05039EB8> 
dt=Image.open(buff) 
print dt --><PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=2630x597 at 0x58C2A90> 
text=textract.process(dt)` 

この行は失敗します。私はTextractは、メモリ内のファイルまたはストリームから読み取るために取得するにはどうすればよいmust be encoded string without NULL bytes, not str

:私は

text=textract.process(buff.getvalue()) 

をすればTextractは、私はエラーを取得する JpegImageFile を読み取ることができませんか?

答えて

0

解決策が見つかりました。メモリ内ファイルは、従来のコードを処理する方法ではありません。 jpg抽出をハードコーディングtempfileにルーティングしました。

tempfile.NamedTemporaryFile 

データストリームを一時ファイルに書き込んでtextract.processするのは少し面倒です。 BytesIO/StringIOの方法でバイトストリームをtextractにトパスする方法がわかりませんでした。 Textract docsによると、それはファイルを期待しています。更新された回避策のコードスニペット:

pdf = file('file name', "rb").read() 

startmark = "\xff\xd8" 
startfix = 0 
endmark = "\xff\xd9" 
endfix = 2 
i = 0 

njpg = 0 
while True: 
    istream = pdf.find("stream", i) 
    if istream < 0: 
     break 
    istart = pdf.find(startmark, istream, istream+20) 
    if istart < 0: 
    i = istream+20 
     continue 
    iend = pdf.find("endstream", istart) 
    if iend < 0: 
     raise Exception("Didn't find end of stream!") 
    iend = pdf.find(endmark, iend-20) 
    if iend < 0: 
     raise Exception("Didn't find end of JPG!") 

    istart += startfix 
    iend += endfix 
    print "JPG %d from %d to %d" % (njpg, istart, iend) 
    jpg = pdf[istart:iend] 

    njpg += 1 
    i = iend 

import tempfile 
temp=tempfile.NamedTemporaryFile(delete=False,suffix='.jpg') 
temp.write(jpg) 
temp.close() 
text=textract.process(temp.name) 
print text 

Info:Python 2.7 on Win7; textractが実際にコードの素晴らしい作品ですので、これは、誰かを助けUTF-8エンコーディング

reload(sys) 
sys.setdefaultencoding('UTF8'). 

希望を余儀なくされました。 pdfからjpegへの変換コードはNed Batchelder Extracting JPGs from PDFs(2007)です。

関連する問題