WIA Scan
The following code sample needed to be rehashed a little as A.I. couldn’t quite get there with it but I eventually made it work. A simple scan command line with Windows image Acquisition API.
import argparse
import os
import sys
import win32com.client
def main():
parser = argparse.ArgumentParser(description='Scan images from a WIA scanner.')
parser.add_argument('--colour', action='store_true', help='scan in colour (default is black and white)')
parser.add_argument('--output', required=True, help='output file path')
parser.add_argument('--y', action='store_true', help='overwrite output file without warning')
args = parser.parse_args()
# Check if output file already exists
if os.path.isfile(args.output):
if args.y:
os.remove(args.output)
else:
print(f"File '{args.output}' already exists. Use --y to overwrite.", file=sys.stderr)
sys.exit(1)
wia = win32com.client.Dispatch('WIA.CommonDialog')
scanner = wia.ShowSelectDevice()
img_type = 'Color' if args.color else 'Grayscale'
item = scanner.Items(1)
img_file = item.Transfer()
file_path = os.path.abspath(args.output)
img_file.SaveFile(file_path)
print(f'Successfully saved scanned image to {file_path}')
if __name__ == '__main__':
main()
The command line options are
–colour
–y
–output
If you omit –colour then you get greyscale
To force overwrite a jpeg file (JPG) use –y
And –output should be in quotes its the full file path you want to save