Untitled
unknown
plain_text
3 years ago
1.8 kB
9
Indexable
from barcode import Code128
from barcode.writer import ImageWriter
from PIL import Image, ImageDraw, ImageOps
def generate_barcode(product_code):
writer = ImageWriter()
writer.dpi = 300
barcode_image = Code128(product_code, writer=writer)
output_filename = 'temp_barcode'
barcode_image.save(output_filename)
raw_image = Image.open(output_filename + ".png").convert('1') # Convert the image to 1-bit mode
dpi = 300 # Use a fixed DPI value (adjust it according to your printer's DPI)
page_size_mm = (25.4, 54)
page_size_pixels = tuple(int(dpi * page_size_mm[i] / 25.4) for i in (0, 1))
desired_width = page_size_pixels[1] - 10 # Subtract a small margin
desired_height = page_size_pixels[0] - 10 # Subtract a small margin
# Swap the foreground and background colors
raw_image = ImageOps.invert(raw_image)
# Rotate the barcode image
raw_image = raw_image.rotate(90, expand=True)
# Create a new image with desired size and DPI
final_image = Image.new('1', (desired_width, desired_height), color='white')
final_image.info['dpi'] = (dpi, dpi)
# Draw the barcode onto the new image
draw = ImageDraw.Draw(final_image)
barcode_width, barcode_height = raw_image.size
# Resize the barcode image to fit the paper dimensions
aspect_ratio = float(barcode_width) / float(barcode_height)
new_height = desired_height
new_width = int(new_height * aspect_ratio)
resized_image = raw_image.resize((new_width, new_height), Image.LANCZOS)
# Center the barcode on the new image
x_pos = (desired_width - new_width) // 2
y_pos = (desired_height - new_height) // 2
draw.bitmap((x_pos, y_pos), resized_image, fill='black')
# Save the final image
final_image.save(output_filename + ".png")
return output_filename
Editor is loading...