Example #1
0
def ReduceImageFileSize(inputFolder, outputFolder, imageQuality):
    processedFiles = 0
    changedFiles = 0
    unchangedFiles = 0
    allFilePaths = IM.GetListOfAllFilePaths(inputFolder)
    for filePath in allFilePaths:
        inputDirectory, inputFile = os.path.split(filePath)
        newFilePath = IM.GetUniqueFile(
            filePath.replace(inputFolder, outputFolder))

        if inputFile.lower().endswith((".jpg", ".jpeg")):
            try:
                img = Image.open(filePath)
                if not os.path.exists(os.path.dirname(newFilePath)):
                    os.makedirs(os.path.dirname(newFilePath))
                img.save(newFilePath, quality=imageQuality)
                changedFiles += 1

            except Exception as ex:
                logger.info(
                    "The following file could not be processed: \"{}\" - {}".
                    format(filePath, ex))

        else:
            IM.CopyFile(filePath, newFilePath)
            unchangedFiles += 1

        processedFiles += 1
        Progress.PrintProgress(processedFiles)

    logger.info(
        "Processed Files: {} | ChangedFiles: {} | Unchanged Files: {}".format(
            processedFiles, changedFiles, unchangedFiles))
def RotateImages(inputFolder, outputFolder):
    processedFiles = 0
    # iterate through all files including subdirectories
    for path, subDirectories, files in os.walk(inputFolder):
        # create output path
        if not os.path.exists(path.replace(inputFolder, outputFolder)):
            os.makedirs(path.replace(inputFolder, outputFolder))

        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg')):
                filePath = os.path.join(path, file)

                # get exif data
                exifDictionary = piexif.load(filePath)
                orientation = exifDictionary["0th"][
                    piexif.ImageIFD.Orientation]

                if orientation == 1 and inputFolder != outputFolder:
                    copy2(filePath, filePath.replace(inputFolder,
                                                     outputFolder))

                elif orientation > 1:
                    # set orientation to 1 and delete thumbnail data
                    exifDictionary["0th"][piexif.ImageIFD.Orientation] = 1
                    exifDictionary.pop("thumbnail")

                    # load image
                    image = Image.open(filePath)

                    # rotate image
                    if orientation == 2:
                        image = image.transpose(Image.FLIP_LEFT_RIGHT)
                    elif orientation == 3:
                        image = image.rotate(180)
                    elif orientation == 4:
                        image = image.rotate(180).transpose(
                            Image.FLIP_LEFT_RIGHT)
                    elif orientation == 5:
                        image = image.rotate(-90, expand=True).transpose(
                            Image.FLIP_LEFT_RIGHT)
                    elif orientation == 6:
                        image = image.rotate(-90, expand=True)
                    elif orientation == 7:
                        image = image.rotate(90, expand=True).transpose(
                            Image.FLIP_LEFT_RIGHT)
                    elif orientation == 8:
                        image = image.rotate(90, expand=True)

                    # save image with updated exif data
                    image.save(filePath.replace(inputFolder, outputFolder),
                               "JPEG",
                               quality=95,
                               exif=piexif.dump(exifDictionary))
            else:
                copy2(filePath, filePath.replace(inputFolder, outputFolder))

            # show progress
            processedFiles = processedFiles + 1
            Progress.PrintProgress(processedFiles)
Example #3
0
def ChangeCaptureDate(inputFolder, outputFolder, timeDifferenceInSeconds):
    processedFiles = 0
    changedFiles = 0
    unchangedFiles = 0
    allFilePaths = IM.GetListOfAllFilePaths(inputFolder)
    for filePath in allFilePaths:
        inputDirectory, inputFile = os.path.split(filePath)
        newFilePath = IM.GetUniqueFile(
            filePath.replace(inputFolder, outputFolder))
        IM.CopyFile(filePath, newFilePath)

        if inputFile.lower().endswith(('.jpg', '.jpeg')):
            captureTime = ""
            try:
                exif_dict = piexif.load(filePath)
                exifData = exif_dict.get("Exif")

                if exifData != {}:
                    captureTime_original = exifData[36867]
                    captureTime = str(captureTime_original)[2:-1]
                    captureTime = datetime.strptime(captureTime,
                                                    "%Y:%m:%d %H:%M:%S")
                    newCaptureTime = captureTime + timedelta(
                        seconds=timeDifferenceInSeconds)
                    newCaptureTime_string = newCaptureTime.strftime(
                        "%Y:%m:%d %H:%M:%S")
                    newCaptureTime_bytes = bytes(newCaptureTime_string,
                                                 'utf-8')
                    exif_dict["Exif"][36867] = newCaptureTime_bytes
                    exif_bytes = piexif.dump(exif_dict)
                    piexif.insert(exif_bytes, newFilePath)
                    changedFiles += 1

                else:
                    unchangedFiles += 1

            except Exception:
                logger.info(
                    "No capture time found for: \"{}\"".format(filePath))

        else:
            unchangedFiles += 1

        processedFiles += 1
        Progress.PrintProgress(processedFiles)

    logger.info(
        "Processed Files: {} | ChangedFiles: {} | Unchanged Files: {}".format(
            processedFiles, changedFiles, unchangedFiles))
def SetNameAsCaptureDate(inputFolder, outputFolder):
    processedFiles = 0
    changedFiles = 0
    unchangedFiles = 0
    allFilePaths = IM.GetListOfAllFilePaths(inputFolder)
    for filePath in allFilePaths:
        inputDirectory, inputFile = os.path.split(filePath)
        newFilePath = IM.GetUniqueFile(
            filePath.replace(inputFolder, outputFolder))
        IM.CopyFile(filePath, newFilePath)

        if inputFile.lower().endswith((".jpg", ".jpeg")):
            try:
                captureTime = datetime.strptime(inputFile[0:15],
                                                "%Y%m%d_%H%M%S")
            except Exception:
                try:
                    captureTime = datetime.strptime(inputFile[0:8], "%Y%m%d")
                except Exception:
                    logger.info(
                        "Unable to set capture time for: \"{}\"".format(
                            filePath))
                    continue

            captureTime_string = captureTime.strftime("%Y:%m:%d %H:%M:%S")
            exif_dict = piexif.load(filePath)
            exifData = exif_dict.get("Exif")
            captureTime_bytes = bytes(captureTime_string, 'utf-8')
            exif_dict["Exif"][36867] = captureTime_bytes
            exif_bytes = piexif.dump(exif_dict)
            piexif.insert(exif_bytes, newFilePath)
            changedFiles += 1

        else:
            unchangedFiles += 1

        processedFiles += 1
        Progress.PrintProgress(processedFiles)

    logger.info(
        "Processed Files: {} | ChangedFiles: {} | Unchanged Files: {}".format(
            processedFiles, changedFiles, unchangedFiles))
Example #5
0
def UnifyPictureNames(inputFolder, outputFolder):
    processedFiles = 0
    renamedFiles = 0
    unchangedFiles = 0
    allFilePaths = IM.GetListOfAllFilePaths(inputFolder)
    for filePath in allFilePaths:
        inputDirectory, inputFile = os.path.split(filePath)
        if inputFile.lower().endswith(('.png', '.jpg', '.jpeg')):
            # get file metadata
            metadata = exifread.process_file(open(filePath, "rb"))
            captureTime = ""
            try:
                captureTime = str(metadata["EXIF DateTimeOriginal"])
            except Exception:
                logger.info(
                    "No capture time found for: \"{}\"".format(filePath))

            # pictures with creation timestamp
            if captureTime != "":
                _, fileExtension = os.path.splitext(inputFile)
                newFile = captureTime.replace(":", "").replace(
                    " ", "_") + fileExtension.lower()
                IM.CopyFile(
                    filePath,
                    IM.GetUniqueFile(
                        os.path.join(
                            inputDirectory.replace(inputFolder, outputFolder),
                            newFile)))
                logger.debug("{} --> {}".format(
                    filePath,
                    os.path.join(
                        inputDirectory.replace(inputFolder, outputFolder),
                        newFile)))
                renamedFiles += 1
            # WhatsApp images
            elif "WA" in inputFile:
                newFile = inputFile.replace("IMG-", "")
                IM.CopyFile(
                    filePath,
                    IM.GetUniqueFile(
                        os.path.join(
                            inputDirectory.replace(inputFolder, outputFolder),
                            newFile)))
                logger.debug("{} --> {}".format(
                    filePath,
                    os.path.join(
                        inputDirectory.replace(inputFolder, outputFolder),
                        newFile)))
                renamedFiles += 1
            # files without creation timestamp
            else:
                IM.CopyFile(
                    filePath,
                    IM.GetUniqueFile(
                        filePath.replace(inputFolder, outputFolder)))
                unchangedFiles += 1
        else:
            IM.CopyFile(
                filePath,
                IM.GetUniqueFile(filePath.replace(inputFolder, outputFolder)))
            unchangedFiles += 1

        processedFiles += 1
        Progress.PrintProgress(processedFiles)

    logger.info(
        "Processed Files: {} | RenamedFiles: {} | Unchanged Files: {}".format(
            processedFiles, renamedFiles, unchangedFiles))
Example #6
0
def UnifyPictureNames(inputFolder, outputFolder):
    processedFiles = 0
    renamedFiles = 0
    unchangedFiles = 0
    for path, subDirectories, files in os.walk(inputFolder):
        # create output path
        if not os.path.exists(path.replace(inputFolder, outputFolder)):
            os.makedirs(path.replace(inputFolder, outputFolder))

        for file in files:
            filePath = os.path.join(path, file)
            if file.lower().endswith(('.png', '.jpg', '.jpeg')):
                # get file metadata
                metadata = exifread.process_file(open(filePath, "rb"))
                captureTime = ""
                try:
                    captureTime = str(metadata["EXIF DateTimeOriginal"])
                except Exception:
                    logging.info(
                        "{0} - No capture time found for: \"{1}\"".format(
                            GetFormattedDatetimeNow(), filePath))

                # pictures with creation timestamp
                if captureTime != "":
                    _, fileExtension = os.path.splitext(file)
                    newFile = captureTime.replace(":", "").replace(
                        " ", "_") + fileExtension.lower()
                    copy2(
                        filePath,
                        GetUniqueFile(path.replace(inputFolder, outputFolder),
                                      newFile))
                    logging.debug("{0} - {1} --> {2}".format(
                        GetFormattedDatetimeNow(), filePath,
                        os.path.join(path.replace(inputFolder, outputFolder),
                                     newFile)))
                    renamedFiles += 1
                # WhatsApp images
                elif "WA" in file:
                    newFile = file.replace("IMG-", "")
                    copy2(
                        filePath,
                        GetUniqueFile(path.replace(inputFolder, outputFolder),
                                      newFile))
                    logging.debug("{0} - {1} --> {2}".format(
                        GetFormattedDatetimeNow(), filePath,
                        os.path.join(path.replace(inputFolder, outputFolder),
                                     newFile)))
                    renamedFiles += 1
                # files without creation timestamp
                else:
                    copy2(
                        filePath,
                        GetUniqueFile(path.replace(inputFolder, outputFolder),
                                      file))
                    unchangedFiles += 1
            else:
                copy2(
                    filePath,
                    GetUniqueFile(path.replace(inputFolder, outputFolder),
                                  file))
                unchangedFiles += 1

            processedFiles += 1
            Progress.PrintProgress(processedFiles)

    logging.info(
        "{0} - Processed Files: {1} | RenamedFiles: {2} | Unchanged Files: {3}"
        .format(GetFormattedDatetimeNow(), processedFiles, renamedFiles,
                unchangedFiles))