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

2

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)

Neckerchief answered 14/7, 2016 at 6:24 Comment(0)
S
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

Stylographic answered 14/7, 2016 at 6:32 Comment(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 youNeckerchief
Well, this accepted answer was what drove me over the line to be able to comment, so: Thanks, will post code from now on! :)Stylographic
N
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))
Nainsook answered 15/5, 2020 at 20:7 Comment(2)
That doesn't reduce the size of the files. They will still be 50MB.Hefty
Does this actually change the formatting of the picture, or does it just change the extension name?Jeconiah

© 2022 - 2024 — McMap. All rights reserved.