Adjusting size of barcode image output

Viewed 5159

I am trying to adjust the size of a barcode output

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')

The error I am getting is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'module_width' is not defined

I dont really understand how to use the documentation found here: https://pythonhosted.org/pyBarcode/writers/index.html

3 Answers

After you generated an image of any size you can resize it using 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

more on PIL.Image.resize

I solved this problem by changing this line

code128.save('filename', {"module_width":0.35, "module_height":10, "font_size": 18, "text_distance": 1, "quiet_zone": 3})

without using another liabrary.

See that! I solved my problem exactly like this, when saving, I did it as follows::

IMPORTANT: Without another library!

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))

Example:

Here U can see the image output.

Related