pythonpython-imaging-librarybarcodebytesio

Trying to convert an image to a Stream for use with Spire.Barcode ScanStream functionality


I am currently creating a application which can read barcodes from images and then display the images.

I am using Spire.Barcode as my library as it seems to have the best recognition rate. Currently I have to load the image twice, once to scan for a barcode then a second time to load it into the UI

The user selects a folder, then all the images in the folder are scanned for a barcode, then opened again, resized and saved into memory to be displayed in the UI

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

The image_path points to the image.

I was hoping there is a way to instead load the image once, pass the image data to the scanner, and then resize and store the data.

Spire does have a function called ScanStream but so far every way I have tried to convert the image to a stream/bytes hasn't worked with the most common error being '_io.BytesIO' object has no attribute 'Ptr' I think it may be something to do with Spire.Barcode being a C Library.

I have tried to use io.BytesIO. I have used PILs built in toBytes() function. I have tried to google this and looked at documentation but I really have no idea.

Not really sure where to go from here. Any help greatly appreciated.


Solution

  • In your code, you are creating a BytesIO stream. However, Spire.Barcode for Python uses a different Stream object. You can adjust your code according to the following example:

    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)
    

    Here is my result:

    enter image description here

    Btw, the BarcodeScanner class of Spire.Barcode for Python provides several functions for scanning barcodes from streams. You can choose an appropriate one according to your needs. enter image description here