Python - how to make BMP into JPEG or PDF? so that the file size is not 50MB but less?

user285594 picture user285594 · Jul 14, 2016 · Viewed 14.4k times · Source

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)

Answer

qDot picture qDot · Jul 14, 2016

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