Ошибка подушки: ImageFont генерирует штрих-код со штрих-кодом Code128. Ошибка ОС: невозможно открыть ресурс

У меня очень странная ошибка в моем коде. Я пишу программу на Python, которая генерирует штрих-коды и объединяет их в изображение. Когда я запускаю файл .exe, он выдает ошибку. Однако это странно, потому что когда я запускаю его из VS Code без каких-либо проблем, код работает правильно. Но когда я конвертирую его в файл .exe, выдает ошибку.

Вот код:

def generate_and_save_image(self, filename, dpi=600):
        # Create new image
        image = Image.new("RGB", (1024, 768), "white")
        draw = ImageDraw.Draw(image)

        # Font
        font_path = "C:/Users/RaulV/Desktop/sbar/ARIAL.ttf"
        large_font = ImageFont.load_default()
        
        print("Font Path:", font_path)
        print("Large Font Loaded:", large_font)

        # Generate and add the origin barcode
        barcode_origin = Code128(self.current_origin, writer=ImageWriter())
        barcode_origin.save("barcode_origin")
        barcode_origin_img = Image.open("barcode_origin.png")
        barcode_origin_img = barcode_origin_img.resize((barcode_origin_img.width, barcode_origin_img.height))
        image.paste(barcode_origin_img, (10, 40))
        
        draw.text((20, 10), "ORIGEN", fill = "black", font=large_font)

        # Generate and add the destination barcode
        barcode_destination = Code128(self.current_destination, writer=ImageWriter())
        barcode_destination.save("barcode_destination")
        barcode_destination_img = Image.open("barcode_destination.png")
        barcode_destination_img = barcode_destination_img.resize((barcode_destination_img.width, barcode_destination_img.height)) 
        image.paste(barcode_destination_img, (image.width - barcode_destination_img.width - 10, 40))
        draw.text((image.width - barcode_destination_img.width - 10, 10), "DESTINO", fill = "black", font=large_font)
        
        # Generate and add the scanned barcode
        barcode_scanned = Code128(self.codigo_barras, writer=ImageWriter())
        barcode_scanned.save(f"barcode")
        barcode_scanned_img = Image.open(f"barcode.png")
        
        # Calculate the coordinates to place the barcode in the center of the image
        x = (image.width - barcode_scanned_img.width) // 2
        y = (image.height - barcode_scanned_img.height) // 2 + 50
        
        image.paste(barcode_scanned_img, (x, y))

        # Generate and add the quantity barcode in the bottom right corner
        barcode_quantity = Code128(str(self.cantidad), writer=ImageWriter())
        barcode_quantity.save("barcode_quantity")
        barcode_quantity_img = Image.open("barcode_quantity.png")
        barcode_quantity_img = barcode_quantity_img.resize((barcode_quantity_img.width, barcode_quantity_img.height))
        image.paste(barcode_quantity_img, (image.width - barcode_quantity_img.width - 10, image.height - barcode_quantity_img.height - 10))
        
        # Text with the quantity
        draw.text((image.width - barcode_quantity_img.width - 10, image.height - barcode_quantity_img.height - 30), "CANTIDAD", fill = "black", font=large_font)

        query = ""
        self.cursor.execute(query, (self.codigo_barras))
        result = self.cursor.fetchone()
        if result:
            article_code, description = result
            draw.text((10, image.height-90), f"REF: {article_code}", fill = "black", font=large_font)
            draw.text((10, image.height-30), f"{description}", fill = "black", font=large_font) 
                
        query = ""
        self.cursor.execute(query, (self.current_origin))
        result = self.cursor.fetchone()
        if result:
            cantidadAnterior = result[0]
            draw.text((10, image.height-60), f"Unidades en la ubicacion de origen: {cantidadAnterior}", fill = "black", font=large_font)  
        
        # Save image
        image.save(filename, dpi=(dpi, dpi))

Вот ошибка:

Font Path: C:/Users/RaulV/Desktop/sbar/ARIAL.ttf
Large Font Loaded: <PIL.ImageFont.FreeTypeFont object at 0x0000022DA8EB6ED0>
Exception in Tkinter callback
Traceback (most recent call last):
  File "tkinter\__init__.py", line 1967, in __call__
  File "combinedApp.py", line 759, in close_selected_boxes
  File "combinedApp.py", line 842, in generate_and_save_image
  File "barcode\base.py", line 64, in save
  File "barcode\codex.py", line 255, in render
  File "barcode\base.py", line 100, in render
  File "barcode\writer.py", line 269, in render
  File "barcode\writer.py", line 440, in _paint_text
  File "PIL\ImageFont.py", line 807, in truetype
  File "PIL\ImageFont.py", line 804, in freetype
  File "PIL\ImageFont.py", line 244, in __init__
OSError: cannot open resource

Строка 759: self.generate_and_save_image(filename) Строка 842: barcode_origin.save("barcode_origin")

Я тоже пробовал использовать шрифт по умолчанию: large_font = ImageFont.load_default(), но получаю ту же ошибку.

Когда я конвертирую .py в .exe, я использую pyinstaller, я попытался добавить шрифт в exe и получаю ту же ошибку. Это команда для преобразования:

pyinstaller --noconfirm --onefile --console --add-data "C:/Users/RaulV/Desktop/Barcodes/arial.ttf;."  "C:/Users/RaulV/Desktop/Barcodes/combinedApp.py"

Теперь я пытаюсь использовать простой код и получаю ту же ошибку:

    def generate_barcode(code, filename):
        code128 = barcode.get_barcode_class('code128')
        barcode_instance = code128(code, writer=ImageWriter())
        barcode_instance.save(filename)

    generate_barcode('123456789', 'barcode.png')
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
1
0
61
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Я нашел решение.

Мне нужно создать объект ImageWriter перед инициализацией Code128, например:

font_path = 'your_path'
writer = ImageWriter()
writer.font_path = font_path 
writer.format = 'png'
barcode_origin = Code128(self.current_origin, writer=writer)

Другие вопросы по теме