10

I have a scanner when i scan the page it makes a BMP file but the size per page is 50MB. How do i tell Python, make it JPEG and small size.

rv = ss.XferImageNatively()
if rv:
(handle, count) = rv
twain.DIBToBMFile(handle,'imageName.bmp')

how do you tell him to make it JPEG or PDF? ( Native transfers are always uncompressed images, so your image size will be: (width-in-inches * dpi) * (height-in-inches * dpi) * bytes-per-pixel)

2 Answers2

13

You can use something like PIL (http://www.pythonware.com/products/pil/) or Pillow (https://github.com/python-pillow/Pillow), which will save the file in the format you specify based on the filename.

The python TWAIN module will return the bitmap from DIBToBMFile as a string if no filename is specified, so you can feed that string into one of the image libraries to use as a buffer. Otherwise, you can just save to a file, then open that file and resave it, but that's a rather roundabout way of doing things.

EDIT: see (lazy mode on)

from PIL import Image
img = Image.open('C:/Python27/image.bmp')
new_img = img.resize( (256, 256) )
new_img.save( 'C:/Python27/image.png', 'png')

Output:

enter image description here

qDot
  • 430
  • 3
  • 8
  • 2
    See EDIT section, post always code sample please, it remain better for few years for other users who have similar problem in there research and development. thank you –  Jul 14 '16 at 08:16
  • Well, this accepted answer was what drove me over the line to be able to comment, so: Thanks, will post code from now on! :) – qDot Jul 14 '16 at 21:49
4

For batch converting:

from PIL import Image
import glob
ext = input('Input the original file extension: ')
new = input('Input the new file extension: ')

# Checks to see if a dot has been input with the images extensions.
# If not, it adds it for us:
if '.' not in ext.strip():
    ext = '.'+ext.strip()
if '.' not in new.strip():
    new = '.'+new.strip()

# Creates a list of all the files with the given extension in the current folder:
files = glob.glob('*'+ext)

# Converts the images:
for f in files:
    im = Image.open(f)
    im.save(f.replace(ext,new))