类型错误:需要类似字节的对象,而不是"绘图"



我正在尝试将Alpha数值转换为PNG,然后转换为ZPL格式。它们都有不同的库,独立使用时效果良好。看看代码:

from base64 import b64encode
from reportlab.lib import units
from reportlab.graphics import renderPM
from reportlab.graphics.barcode import createBarcodeDrawing
from reportlab.graphics.shapes import Drawing
import os
def get_barcode(value, width, barWidth = 0.05 * units.inch, fontSize = 30, humanReadable = True):
barcode = createBarcodeDrawing('Code128', value = value, barWidth = barWidth, fontSize = fontSize)
drawing_width = width
barcode_scale = drawing_width / barcode.width
drawing_height = barcode.height * barcode_scale
drawing = Drawing(drawing_width, drawing_height)
drawing.scale(barcode_scale, barcode_scale)
drawing.add(barcode, name='barcode')
return drawing
sku = []      #rough data
path = r'C:UsersRahulDesktopBarcodes'
for i in range(0,10):
sku.append('A10{}'.format(i)) 
for i in sku:
barcode = get_barcode(value = i, width = 600)
barcode.save(formats=['PNG'],outDir=path,fnRoot=i)

这将生成PNG格式的条形码现在向ZPL的转换是这样的:

from zplgrf import GRF
with open(r'C:UsersRahulDesktopBarcodesA100.png','rb') as image:
grf = GRF.from_image(image.read(), 'DEMO')
grf.optimise_barcodes()
print(grf.to_zpl())

输出:

~DGR:DEMO.GRF,5400,75,:Z64:eJztlrENxSAMRI8qJSMwCpv9hM0YhRFSUnxxQelSfn0jEXQuaECW3/kMAHdsTBUfwNWQEQhEeDbEtmVHJhZXEVn2b1+ZydI8j36whr6HR3i7VIZV/ZPqXB3QsIPnsKomARznKwEKUIACFOAkWgnwdYCGFl3+JyPAtwMaVqVnQreoZnAqX60HOE6r9QANO6gZ/F2rCxESD8A=:4C36^XA^MMC,Y^PON^MNY^FO0,0^XGR:DEMO.GRF,1,1^FS^PQ1,0,0,N^XZ^XA^IDR:DEMO.GRF^FS^XZ

我想做的是消除保存文件,然后再次读取转换的过程,所以我做了这个:

for i in sku:
barcode = get_barcode(value = i, width = 600)
barcode.save(formats=['PNG'],fnRoot=i)
print(barcode)
grf = GRF.from_image(barcode, 'DEMO')
grf.optimise_barcodes()
print(grf.to_zpl())

但我得到以下错误:

TypeError:需要类似字节的对象,而不是"Drawing">

如何将以下对象转换为"类似字节"的对象??

<reportlab.graphics.shapes.Drawing object at 0x000001BF2C59DF28>

错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-2b88439d6661> in <module>
3     barcode.save(formats=['PNG'],fnRoot=i)
4     print(barcode)
----> 5     grf = GRF.from_image(barcode, 'DEMO')
6     grf.optimise_barcodes()
7     print(grf.to_zpl())
~Anaconda3libsite-packageszplgrf__init__.py in from_image(cls, image, filename)
354         """
355 
--> 356         source = Image.open(BytesIO(image))
357         source = source.convert('1')
358         width = int(math.ceil(source.size[0] / 8.0))
TypeError: a bytes-like object is required, not 'Drawing'
要调用GRF.from_image,需要传递一个类似字节的对象。目前,您已经将Drawing保存为png文件,然后将函数传递给它。相反,您应该打开保存的png文件,并将读取的对象传递给from_image,如:
with open(barcode_file, "rb") as image:
grf = GRF.from_image(image.read(), "DEMO")
os.remove(barcode_file)

其中barcode_file是保存Drawing的路径。os.remove可用于在读取临时文件之后移除临时文件。

为了避免创建这样的临时文件,可以使用Drawing类的asString方法并将结果传递给from_image:

grf = GRF.from_image(barcode.asString("png"), "DEMO")

相关内容

  • 没有找到相关文章

最新更新