尝试将图像转换为流以用于Spire.Barcode ScanStream功能

0 投票
1 回答
46 浏览
提问于 2025-04-12 22:53

我现在正在制作一个应用程序,可以从图片中读取条形码,然后显示这些图片。

我使用的是Spire.Barcode这个库,因为它的识别率看起来是最好的。目前我需要加载图片两次,第一次是扫描条形码,第二次是把它加载到用户界面上。

用户选择一个文件夹,然后文件夹中的所有图片都会被扫描以查找条形码,接着再打开这些图片,调整大小并保存到内存中,以便在用户界面上显示。

def scan_single_image_for_barcode(image_path):
    try:
        barcode = spire.BarcodeScanner.ScanFileWithBarCodeType(image_path, spire.BarCodeType.Code39)
        print(f"Barcode From spire= {barcode} and barcode {barcode[0]}")
        if barcode[0] is not None:
            barcode = barcode[0]
    except Exception as e:
        print(f"Error scanning image '{image_path}': {e}")
        barcode = None
    return barcode

image_path指向那张图片。

我希望能有一种方法,只加载一次图片,把图片数据传给扫描器,然后再调整大小并存储这些数据。

Spire确实有一个叫ScanStream的功能,但到目前为止,我尝试的每种将图片转换为流或字节的方法都没有成功,最常见的错误是 '_io.BytesIO' object has no attribute 'Ptr' 我觉得这可能和Spire.Barcode是一个C语言库有关。

我尝试过使用io.BytesIO,也用过PIL内置的toBytes()函数。我试着在网上搜索这个问题,也看了文档,但我真的没有头绪。

现在不太确定接下来该怎么做。非常感谢任何帮助。

1 个回答

0

在你的代码中,你创建了一个 BytesIO 流。但是,Spire.Barcode for Python 使用的是不同的流对象。你可以根据下面的例子来调整你的代码:

from spire.barcode import *

image_path = "Code39.png"

with open(image_path, "rb") as file:
    image_bytes = file.read()

stream = Stream(image_bytes)

scan_result = BarcodeScanner.ScanOneStream(stream)

print(scan_result)

这是我的结果:

这里输入图片描述

顺便提一下,Spire.Barcode for Python 的 BarcodeScanner 类提供了几种从流中扫描条形码的功能。你可以根据自己的需求选择合适的功能。

这里输入图片描述

撰写回答