Python条码生成

2024-05-09 20:55:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用用于python的elaphe包生成ean-13条码图像。该包是使用位于https://pypi.python.org/pypi/elaphe的tar文件从源安装的。

当我运行代码时:

BARCODE_IMAGE_PATH = "/tmp/"

def create_barcode_image(product_barcode):

    path = BARCODE_IMAGE_PATH + product_barcode + '.png'

    img = barcode('ean13', product_barcode, 
                  options=dict(includetext=True, height=0.4), margin=1)
    img.save(path, 'PNG')

    return path 

从python解释器看来,它工作得很好。按照我指定的路径生成正确的条形码。当我使用web.py作为我的web框架从apache运行它时,我收到一个错误:

Traceback (most recent call last):
  ...
     img_path = create_barcode_image(barcode)
   File "/var/www/py/documents/barcode_images.py", line 27, in create_barcode_image
     img.save(path, 'PNG')
   File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 1406, in save
     self.load()
   File "/usr/local/lib/python2.7/dist-packages/PIL/EpsImagePlugin.py", line 283, in load
     self.im = Ghostscript(self.tile, self.size, self.fp)
   File "/usr/local/lib/python2.7/dist-packages/PIL/EpsImagePlugin.py", line 75, in Ghostscript
     raise IOError("gs failed (status %d)" % status)
 IOError: gs failed (status 256) 

有人知道是什么导致了这个错误或者如何调试它吗?


Tags: pathinpyimageselfimgsavelib
3条回答

如果barcode无效,则可能导致此错误。你应该首先确定这是你所期望的。打印出来,或写入文件,或使用调试器

添加一些可以遍历的调试语句:

import sys

BARCODE_IMAGE_PATH = "/tmp/"

def create_barcode_image(product_barcode):

    print >> sys.stderr, "product_barcode: %s" % product_barcode

    path = BARCODE_IMAGE_PATH + product_barcode + '.png'

    print >> sys.stderr, "path: %s" % path

    img = barcode('ean13', product_barcode, 
                  options=dict(includetext=True, height=0.4), margin=1)

    print >> sys.stderr, "img data: %s" % img.tostring()

    img.save(path, 'PNG')

    print >> sys.stderr, "Saved to %s" % path

    return path 

那么在你的壳里:

$ tail -F /var/log/httpd/error.log # or wherever you put it

您正在寻找:第一个:输出“product_barcode: ...”。希望这不是空白。如果是,那么问题就在其他地方,可能在您的服务器配置中。然后输出“img data: ...”。希望是png而不是空白。如果是空的,那么问题就在于您的ghostscript安装。

这是一种非常基本的调试方法,我觉得对于小项目来说,插入一些调试语句也很容易,而不是搞乱调试器,因为调试器很难正确设置。

堆栈跟踪表明barcode()返回的图像是PostScript。PIL然后尝试运行GhostScript(gs)将图像转换为所需的输出格式PNG

如果你看一下description of elaphe,你会发现上面写着:

It generates barcode symbol as PostScript code fragment using BWIPP.

是否安装了GhostScript?

也就是说,我建议您尝试pyBarcode,因为它除了PIL之外没有任何依赖项。

相关问题 更多 >