简体   繁体   中英

How do I write code to use the tifffile library to read TIFF files and convert them to JPEGs?

I am trying to write a Python program that will open a TIFF file that has transparencies on it and create a JPEG while also keeping the TIFF file. I've tried Pillow but it won't process TIFFs that have transparencies on them and I've tried imagecodecs but sometimes it can't open certain TIFF files for whatever reason. A suggestion has been to use tifffile but I have no idea the syntax to use to write this. Can anyone assist me with this? Here is my current code using imagecodecs:

import shutil
import os
import io
import stat
import time
import datetime
from dateutil import parser
from PIL import Image
from imagecodecs import imread, imwrite

imwrite(filepath[:-4] + '.jpg', imread(filepath)[:,:,:3].copy()) # <-- using the imagecodecs library function of imread, make a copy in memory of the TIFF File.
# The :3 on the end of the numpy array is stripping the alpha channel from the TIFF file if it has one so it can be easily converted to a JPEG file.
# Once the copy is made the imwrite function is creating a JPEG file from the TIFF file.
# The [:-4] is stripping off the .tif extension from the file and the + '.jpg' is adding the .jpg extension to the newly created JPEG file.
img = Image.open(filepath[:-4] + '.jpg') # <-- Using the Image.open function from the Pillow library, we are getting the newly created JPEG file and opening it.
img = img.convert('RGB') # <-- Using the convert function we are making sure to convert the JPEG file to RGB color mode.
imageResize = img.resize((2500, 2500)) # <-- Using the resize function we are resizing the JPEG to 2500 x 2500
imageResize.save(filepath[:-4] + '.jpg') # <-- Using the save function, we are saving the newly sized JPEG file over the original JPEG file initially created.

The reason this wasn't working is because the breakpoints for errors were turned on in the IDE so it wouldn't work no matter what as the breakpoints would stop the code regardless. Once the breakpoints were turned off the code worked as expected!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM