Exemplo n.º 1
0
def optimize_png(
    src: Union[pathlib.Path, io.BytesIO],
    dst: Optional[pathlib.Path] = None,
    reduce_colors: Optional[bool] = False,
    max_colors: Optional[int] = 256,
    fast_mode: Optional[bool] = True,
    remove_transparency: Optional[bool] = False,
    background_color: Optional[Tuple[int, int, int]] = (255, 255, 255),
    **options,
) -> Union[pathlib.Path, io.BytesIO]:
    """method to optimize PNG files using a pure python external optimizer

    Arguments:
        reduce_colors: Whether to reduce colors using adaptive color pallette (boolean)
            values: True | False
        max_colors: Maximum number of colors if reduce_colors is True (integer between 1 and 256)
            values: 35 | 64 | 256 | 128 | XX
        fast_mode: Whether to use faster but weaker compression (boolean)
            values: True | False
        remove_transparency: Whether to remove transparency (boolean)
            values: True | False
        background_color: Background color if remove_transparency is True (tuple containing RGB values)
            values: (255, 255, 255) | (221, 121, 108) | (XX, YY, ZZ)"""

    ensure_matches(src, "PNG")

    img = Image.open(src)

    if remove_transparency:
        img = remove_alpha(img, background_color)

    if reduce_colors:
        img, _, _ = do_reduce_colors(img, max_colors)

    if not fast_mode and img.mode == "P":
        img, _ = rebuild_palette(img)

    if dst is None:
        dst = io.BytesIO()
    img.save(dst, optimize=True, format="PNG")
    if isinstance(dst, io.BytesIO):
        dst.seek(0)
    return dst
def optimize_png(t: Task) -> TaskResult:
    """ Try to reduce file size of a PNG image.

        Expects a Task object containing all the parameters for the image processing.

        If file reduction is successful, this function will replace the original
        file with the optimized version and return some report data (file path,
        image format, image color mode, original file size, resulting file size,
        and resulting status of the optimization.

        :param t: A Task object containing all the parameters for the image processing.
        :return: A TaskResult object containing information for single file report.
        """
    img = Image.open(t.src_path)
    orig_format = img.format
    orig_mode = img.mode

    folder, filename = os.path.split(t.src_path)
    temp_file_path = os.path.join(folder + "/~temp~" + filename)
    orig_size = os.path.getsize(t.src_path)
    orig_colors, final_colors = 0, 0

    had_exif = has_exif = False  # Currently no exif methods for PNG files
    if orig_mode == 'P':
        final_colors = orig_colors = len(img.getcolors())

    if t.convert_all or (t.conv_big and is_big_png_photo(t.src_path)):
        # convert to jpg format
        filename = os.path.splitext(os.path.basename(t.src_path))[0]
        conv_file_path = os.path.join(folder + "/" + filename + ".jpg")

        if t.max_w or t.max_h:
            img, was_downsized = downsize_img(img, t.max_w, t.max_h)
        else:
            was_downsized = False

        img = remove_transparency(img, t.bg_color)
        img = img.convert("RGB")

        if t.grayscale:
            img = make_grayscale(img)

        try:
            img.save(conv_file_path,
                     quality=t.quality,
                     optimize=True,
                     progressive=True,
                     format="JPEG")
        except IOError:
            ImageFile.MAXBLOCK = img.size[0] * img.size[1]
            img.save(conv_file_path,
                     quality=t.quality,
                     optimize=True,
                     progressive=True,
                     format="JPEG")

        # Only save the converted file if conversion did save any space
        final_size = os.path.getsize(conv_file_path)
        if t.no_size_comparison or (orig_size - final_size > 0):
            was_optimized = True
            if t.force_del:
                try:
                    os.remove(t.src_path)
                except OSError as e:
                    msg = "Error while replacing original PNG with the " \
                          "new JPEG version."
                    print(f"\n{msg}\n{e}\n")
        else:
            final_size = orig_size
            was_optimized = False
            try:
                os.remove(conv_file_path)
            except OSError as e:
                msg = "Error while removing temporary JPEG converted file."
                print(f"\n{msg}\n{e}\n")

        result_format = "JPEG"
        return TaskResult(t.src_path, orig_format, result_format, orig_mode,
                          img.mode, orig_colors, final_colors, orig_size,
                          final_size, was_optimized, was_downsized, had_exif,
                          has_exif)

    # if PNG and user didn't ask for PNG to JPEG conversion, do this instead.
    else:
        result_format = "PNG"
        if t.remove_transparency:
            img = remove_transparency(img, t.bg_color)

        if t.max_w or t.max_h:
            img, was_downsized = downsize_img(img, t.max_w, t.max_h)
        else:
            was_downsized = False

        if t.reduce_colors:
            img, orig_colors, final_colors = do_reduce_colors(
                img, t.max_colors)

        if t.grayscale:
            img = make_grayscale(img)

        if not t.fast_mode and img.mode == "P":
            img, final_colors = rebuild_palette(img)

        try:
            img.save(temp_file_path, optimize=True, format=result_format)
        except IOError:
            ImageFile.MAXBLOCK = img.size[0] * img.size[1]
            img.save(temp_file_path, optimize=True, format=result_format)

        final_size = os.path.getsize(temp_file_path)

        # Only replace the original file if compression did save any space
        if t.no_size_comparison or (orig_size - final_size > 0):
            shutil.move(temp_file_path, os.path.expanduser(t.src_path))
            was_optimized = True
        else:
            final_size = orig_size
            was_optimized = False
            try:
                os.remove(temp_file_path)
            except OSError as e:
                print(f"\nError while removing temporary file.\n{e}\n")

        return TaskResult(t.src_path, orig_format, result_format, orig_mode,
                          img.mode, orig_colors, final_colors, orig_size,
                          final_size, was_optimized, was_downsized, had_exif,
                          has_exif)
Exemplo n.º 3
0
    def optimize_png(self):
        img = Image.open(self.src_path)
        orig_format = img.format
        orig_mode = img.mode

        folder, filename = os.path.split(self.src_path)

        if folder == '':
            folder = os.getcwd()

        temp_file_path = os.path.join(folder + "/~temp~" + filename)
        orig_size = os.path.getsize(self.src_path)
        orig_colors, final_colors = 0, 0

        had_exif = has_exif = False  # Currently no exif methods for PNG files
        if orig_mode == 'P':
            final_colors = orig_colors = len(img.getcolors())

        if self.convert_all or (self.conv_big and self.is_big_png_photo()):
            # convert to jpg format
            filename = os.path.splitext(os.path.basename(self.src_path))[0]
            conv_file_path = os.path.join(folder + "/" + filename + ".jpg")

            if self.max_w or self.max_h:
                img, was_downsized = downsize_img(img, self.max_w, self.max_h)
            else:
                was_downsized = False

            img = remove_transparency(img, self.bg_color)
            img = img.convert("RGB")

            if self.grayscale:
                img = make_grayscale(img)

            try:
                img.save(conv_file_path,
                         quality=self.quality,
                         optimize=True,
                         progressive=True,
                         format="JPEG")
            except IOError:
                ImageFile.MAXBLOCK = img.size[0] * img.size[1]
                img.save(conv_file_path,
                         quality=self.quality,
                         optimize=True,
                         progressive=True,
                         format="JPEG")

            # Only save the converted file if conversion did save any space
            final_size = os.path.getsize(conv_file_path)
            if self.no_size_comparison or (orig_size - final_size > 0):
                was_optimized = True
                if self.force_del:
                    try:
                        os.remove(self.src_path)
                    except OSError as e:
                        details = 'Error while replacing original PNG with the new JPEG version.'
                        show_img_exception(e, self.src_path, details)
            else:
                final_size = orig_size
                was_optimized = False
                try:
                    os.remove(conv_file_path)
                except OSError as e:
                    details = 'Error while removing temporary JPEG converted file.'
                    show_img_exception(e, self.src_path, details)

            result_format = "JPEG"
            return self.src_path

        # if PNG and user didn't ask for PNG to JPEG conversion, do this instead.
        else:
            result_format = "PNG"
            if self.remove_transparency:
                img = remove_transparency(img, self.bg_color)

            if self.max_w or self.max_h:
                img, was_downsized = downsize_img(img, self.max_w, self.max_h)
            else:
                was_downsized = False

            if self.reduce_colors:
                img, orig_colors, final_colors = do_reduce_colors(
                    img, self.max_colors)

            if self.grayscale:
                img = make_grayscale(img)

            if not self.fast_mode and img.mode == "P":
                img, final_colors = rebuild_palette(img)

            try:
                img.save(temp_file_path, optimize=True, format=result_format)
            except IOError:
                ImageFile.MAXBLOCK = img.size[0] * img.size[1]
                img.save(temp_file_path, optimize=True, format=result_format)

            final_size = os.path.getsize(temp_file_path)

            # Only replace the original file if compression did save any space
            if self.no_size_comparison or (orig_size - final_size > 0):
                shutil.move(temp_file_path, os.path.expanduser(self.src_path))
                was_optimized = True
            else:
                final_size = orig_size
                was_optimized = False
                try:
                    os.remove(temp_file_path)
                except OSError as e:
                    details = 'Error while removing temporary file.'
                    show_img_exception(e, self.src_path, details)

            return self.src_path
def optimize_png(task: Task) -> TaskResult:
    """ Try to reduce file size of a PNG image.

        Expects a Task object containing all the parameters for the image processing.

        If file reduction is successful, this function will replace the original
        file with the optimized version and return some report data (file path,
        image format, image color mode, original file size, resulting file size,
        and resulting status of the optimization.

        :param task: A Task object containing all the parameters for the image processing.
        :return: A TaskResult object containing information for single file report.
        """

    img: Image.Image = Image.open(task.src_path)
    orig_format = img.format
    orig_mode = img.mode

    folder, filename = os.path.split(task.src_path)

    if folder == '':
        folder = os.getcwd()

    orig_size = os.path.getsize(task.src_path)
    orig_colors, final_colors = 0, 0

    had_exif = has_exif = False  # Currently no exif methods for PNG files
    if orig_mode == 'P':
        final_colors = orig_colors = len(img.getcolors())

    if task.convert_all or (task.conv_big and is_big_png_photo(task.src_path)):
        # convert to jpg format
        filename = os.path.splitext(os.path.basename(task.src_path))[0]
        output_path = os.path.join(folder + "/" + filename + ".jpg")

        if task.max_w or task.max_h:
            img, was_downsized = downsize_img(img, task.max_w, task.max_h)
        else:
            was_downsized = False

        img = remove_transparency(img, task.bg_color)
        img = img.convert("RGB")

        if task.grayscale:
            img = make_grayscale(img)

        tmp_buffer = BytesIO()  # In-memory buffer
        try:
            img.save(
                tmp_buffer,
                quality=task.quality,
                optimize=True,
                progressive=True,
                format="JPEG")
        except IOError:
            ImageFile.MAXBLOCK = img.size[0] * img.size[1]
            img.save(
                tmp_buffer,
                quality=task.quality,
                optimize=True,
                progressive=True,
                format="JPEG")

        img_mode = img.mode
        img.close()
        compare_sizes = not (task.no_size_comparison or task.convert_all)
        was_optimized, final_size = save_compressed(task.src_path,
                                                    tmp_buffer,
                                                    force_delete=task.force_del,
                                                    compare_sizes=compare_sizes,
                                                    output_path=output_path)

        result_format = "JPEG"
        return TaskResult(task.src_path, orig_format, result_format,
                          orig_mode, img_mode, orig_colors, final_colors,
                          orig_size, final_size, was_optimized,
                          was_downsized, had_exif, has_exif)

    # if PNG and user didn't ask for PNG to JPEG conversion, do this instead.
    else:
        result_format = "PNG"
        if task.remove_transparency:
            img = remove_transparency(img, task.bg_color)

        if task.max_w or task.max_h:
            img, was_downsized = downsize_img(img, task.max_w, task.max_h)
        else:
            was_downsized = False

        if task.reduce_colors:
            img, orig_colors, final_colors = do_reduce_colors(
                img, task.max_colors)

        if task.grayscale:
            img = make_grayscale(img)

        if not task.fast_mode and img.mode == "P":
            img, final_colors = rebuild_palette(img)

        tmp_buffer = BytesIO()  # In-memory buffer
        try:
            img.save(tmp_buffer, optimize=True, format=result_format)
        except IOError:
            ImageFile.MAXBLOCK = img.size[0] * img.size[1]
            img.save(tmp_buffer, optimize=True, format=result_format)

        img_mode = img.mode
        img.close()
        compare_sizes = not task.no_size_comparison
        was_optimized, final_size = save_compressed(task.src_path,
                                                    tmp_buffer,
                                                    force_delete=task.force_del,
                                                    compare_sizes=compare_sizes)

        return TaskResult(task.src_path, orig_format, result_format, orig_mode,
                          img_mode, orig_colors, final_colors, orig_size,
                          final_size, was_optimized, was_downsized, had_exif,
                          has_exif)