Skip to main content

TWAIN API for accessing scanners, cameras, etc on Windows

Project description

pytwain

This library allows acquiring images from various sources that support TWAIN protocol, e.g. scanners.

To install this library run:

pip install pytwain

Once installed you can run following sample Python script to acquire an image:

from io import BytesIO
import twain
import tkinter
from tkinter import ttk
import logging
import PIL.ImageTk
import PIL.Image

scanned_image = None


def scan():
    global scanned_image
    with twain.SourceManager(root) as sm:
        # this will show UI to allow user to select source
        src = sm.open_source()
        if src:
            src.request_acquire(show_ui=False, modal_ui=False)
            (handle, remaining_count) = src.xfer_image_natively()
            bmp_bytes = twain.dib_to_bm_file(handle)
            img = PIL.Image.open(BytesIO(bmp_bytes), formats=["bmp"])
            width, height = img.size
            factor = 600.0 / width
            # Storing PhotoImage in global variable to prevent it from being deleted once this function exits
            # since PhotoImage has a __del__ destructor
            scanned_image = PIL.ImageTk.PhotoImage(img.resize(size=(int(width * factor), int(height * factor))))
            frm.destroy()
            ttk.Label(root, image=scanned_image).pack(side="left", fill="both", expand=1)
        else:
            print("User clicked cancel")


logging.basicConfig(level=logging.DEBUG)
root = tkinter.Tk()
frm = ttk.Frame(root, padding=10)
frm.grid()
ttk.Button(frm, text="Scan", command=scan).grid(column=0, row=0)
root.mainloop()

Full documentation for the library located here.

This library uses ctypes to access TWAIN API, therefore it does not require compilation and can work with Pypi.

References

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pytwain-2.3.0.tar.gz (29.0 kB view details)

Uploaded Source

File details

Details for the file pytwain-2.3.0.tar.gz.

File metadata

  • Download URL: pytwain-2.3.0.tar.gz
  • Upload date:
  • Size: 29.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.0

File hashes

Hashes for pytwain-2.3.0.tar.gz
Algorithm Hash digest
SHA256 c64a181369577ad600929ad64cb6ad702ec41fd8cf9886d785e3b87516e7b369
MD5 782ad36ac145ed4bc7f4558141e5ec92
BLAKE2b-256 594ee3206ca8de413b086b3a2e42b09cdaa7157d0e2841063433c16141dd3fdc

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page