Last active
September 24, 2024 12:46
-
-
Save nagasudhirpulla/729ac784e74d151771965d332d1431db to your computer and use it in GitHub Desktop.
image compression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from PIL import Image | |
import piexif | |
import glob | |
import pathlib | |
def copyMetadata(srcImgPath, destImgPath): | |
# Open the source image | |
srcImg = Image.open(srcImgPath) | |
# Extract EXIF data from the source image | |
exifData = piexif.load(srcImg.info['exif']) | |
# bug handling for 41729 exif tag (scenetype) | |
if 41729 in exifData['Exif'] and isinstance(exifData['Exif'][41729], int): | |
exifData['Exif'][41729] = str(exifData['Exif'][41729]).encode('utf-8') | |
# Open the destination image | |
destImg = Image.open(destImgPath) | |
# Save the destination image with the source's EXIF data | |
destImg.save(destImgPath, exif=piexif.dump(exifData)) | |
# Copy file attributes for last accessed time and modified time | |
srcImgStats = os.stat(srcImgPath) | |
# set file ownership information (applicable only in unix systems) | |
# os.chown(destImgPath, srcImgStats.st_uid, srcImgStats.st_gid) | |
# set modified time and last accessed time | |
os.utime(destImgPath, (srcImgStats.st_atime, srcImgStats.st_mtime)) | |
def compressImage(srcImgPath, destImgPath, maxWidth, quality=100): | |
# open source image | |
image = Image.open(srcImgPath) | |
# get the image dimensions | |
width, height = image.size | |
# Resize image if necessary | |
if width > maxWidth: | |
newHeight = height*(maxWidth/width) | |
image.thumbnail((maxWidth, newHeight)) | |
# Save the new image | |
outFname = destImgPath | |
print(f"saving {outFname}") | |
image.save(outFname, 'JPEG', quality=quality) | |
# copy metadata from source image to destination image | |
copyMetadata(srcImgPath, destImgPath) | |
# Example usage | |
inpFolder = r"C:\Users\Nagasudhir\Downloads\pics" | |
outFolder = r"C:\Users\Nagasudhir\Downloads\pics1" | |
maxWidth = 1280 | |
qualityPerc = 100 | |
for imgIter, imgPath in enumerate(glob.glob(inpFolder+r"\*.jpg")): | |
print(f"{imgIter} : processing {imgPath}") | |
outFileName = pathlib.Path(imgPath).name | |
outFilePath = os.path.join(outFolder, outFileName) | |
compressImage(imgPath, outFilePath, maxWidth, qualityPerc) | |
print("process complete...") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment