调整条形码图像输出的大小

4

我正在尝试调整条形码的输出大小。

import barcode
from barcode.writer import ImageWriter

bar_class = barcode.get_barcode_class('code128')
barcode = '1234567890'
writer=ImageWriter()
writer.set_options({module_width:2, module_height:2})
code128 = bar_class(barcode, writer)
code128.save('filename')

我收到的错误信息是:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'module_width' is not defined

我其实不太明白如何使用这里找到的文档:https://pythonhosted.org/pyBarcode/writers/index.html

3个回答

6
我通过更改这一行来解决了这个问题。
code128.save('filename', {"module_width":0.35, "module_height":10, "font_size": 18, "text_distance": 1, "quiet_zone": 3})

无需使用其他库。


5

在生成任意大小的图像之后,您可以使用PIL来调整其大小。

import barcode
from barcode.writer import ImageWriter
import PIL
from PIL import Image

bar_class = barcode.get_barcode_class('code128')
barcode = '1234567890'

writer=ImageWriter()
code128 = bar_class(barcode, writer)

code128.save('filename') # save the originally generated image

to_be_resized = Image.open('filename.png') # open in a PIL Image object

newSize = (500, 300) # new size will be 500 by 300 pixels, for example
resized = to_be_resized.resize(newSize, resample=PIL.Image.NEAREST) # you can choose other :resample: values to get different quality/speed results

resized.save('filename_resized.png') # save the resized image

更多关于PIL.Image.resize的内容


这个解决方案是可行的,但是当我使用pyFPDF将图像添加到PDF时,在服务器上预览PDF看起来还好,但是当我下载PDF时,由于某种原因质量会降低,并且无法被条形码阅读器读取。 - Z.Chen
1
也许服务器端正在进行一些压缩处理,请尝试不使用PDF格式,尝试仅上传图像到服务器并从服务器下载,检查质量是否降低。 - Oleg Vorobiov
2
当调整条形码大小时,你必须小心谨慎。像你所做的那样使用NEAREST会改变不同条之间的相对宽度,可能导致无法读取。任何其他选项都会在条的边缘引入一些模糊。 - Mark Ransom

3

看这里!我解决了我的问题,并按照以下方式保存:

重要提示:不需要其他库!

ean = barcode.get('ean13', setbarcodehere, writer=ImageWitoutTextWriter())
filename = ean.save(setfilenamehere, {"module_width":0.35, "module_height":10, "font_size": 18, "text_distance": -3, "quiet_zone": 1})
filename
print('Done! :D, {}'.format(filename))

示例:

您可以看到图像输出.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接