Untitled
unknown
plain_text
2 years ago
1.4 kB
3
Indexable
from PIL import Image def generate_barcode(product_code): Code128 = barcode.get_barcode_class('code128') writer = ImageWriter() 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)) writer.dpi = dpi barcode_image = Code128(product_code, writer=writer) output_filename = 'temp_barcode' barcode_image.save(output_filename) # Rotate the image by 90 degrees image = Image.open(output_filename + ".png") rotated_image = image.rotate(270, expand=True) # Resize the barcode image while maintaining aspect ratio desired_width = page_size_pixels[1] - 10 # Subtract a small margin desired_height = page_size_pixels[0] - 10 # Subtract a small margin aspect_ratio = float(rotated_image.width) / float(rotated_image.height) new_height = int(desired_width / aspect_ratio) resized_image = rotated_image.resize((desired_width, new_height), Image.LANCZOS) # Paste the resized image onto a new blank image with exact desired dimensions final_image = Image.new("RGBA", (desired_width, desired_height), (255, 255, 255, 255)) paste_position = (0, (desired_height - new_height) // 2) final_image.paste(resized_image, paste_position) final_image.save(output_filename + ".png") return output_filename
Editor is loading...