# Path: sphinx_gallery/utils.py
# def scale_image(in_fname, out_fname, max_width, max_height):
#     """Scales an image with the same aspect ratio centered in an
#        image box with the given max_width and max_height
#        if in_fname == out_fname the image can only be scaled down
#     """
#     # local import to avoid testing dependency on PIL:
#     Image = _get_image()
#     img = Image.open(in_fname)
#     # XXX someday we should just try img.thumbnail((max_width, max_height)) ...
#     width_in, height_in = img.size
#     scale_w = max_width / float(width_in)
#     scale_h = max_height / float(height_in)
# 
#     if height_in * scale_w <= max_height:
#         scale = scale_w
#     else:
#         scale = scale_h
# 
#     if scale >= 1.0 and in_fname == out_fname:
#         return
# 
#     width_sc = int(round(scale * width_in))
#     height_sc = int(round(scale * height_in))
# 
#     # resize the image using resize; if using .thumbnail and the image is
#     # already smaller than max_width, max_height, then this won't scale up
#     # at all (maybe could be an option someday...)
#     img = img.resize((width_sc, height_sc), Image.BICUBIC)
#     # img.thumbnail((width_sc, height_sc), Image.BICUBIC)
#     # width_sc, height_sc = img.size  # necessary if using thumbnail
# 
#     # insert centered
#     thumb = Image.new('RGBA', (max_width, max_height), (255, 255, 255, 0))
#     pos_insert = ((max_width - width_sc) // 2, (max_height - height_sc) // 2)
#     thumb.paste(img, pos_insert)
# 
#     try:
#         thumb.save(out_fname)
#     except IOError:
#         # try again, without the alpha channel (e.g., for JPEG)
#         thumb.convert('RGB').save(out_fname)
# 
# def optipng(fname, args=()):
#     """Optimize a PNG in place.
# 
#     Parameters
#     ----------
#     fname : str
#         The filename. If it ends with '.png', ``optipng -o7 fname`` will
#         be run. If it fails because the ``optipng`` executable is not found
#         or optipng fails, the function returns.
#     args : tuple
#         Extra command-line arguments, such as ``['-o7']``.
#     """
#     if fname.endswith('.png'):
#         # -o7 because this is what CPython used
#         # https://github.com/python/cpython/pull/8032
#         try:
#             subprocess.check_call(
#                 ['optipng'] + list(args) + [fname],
#                 stdout=subprocess.PIPE,
#                 stderr=subprocess.PIPE)
#         except (subprocess.CalledProcessError, IOError):  # FileNotFoundError
#             pass


import importlib
import inspect
import os
import sys
import re
    import matplotlib
    import matplotlib.pyplot as plt
from textwrap import indent
from pathlib import PurePosixPath
from warnings import filterwarnings
from sphinx.errors import ExtensionError
from .utils import scale_image, optipng
    from matplotlib.animation import Animation
    from matplotlib.animation import FFMpegWriter, ImageMagickWriter
    from mayavi import mlab
def mayavi_scraper(block, block_vars, gallery_conf):
    """Scrape Mayavi images.

    Parameters
    ----------
    block : tuple
        A tuple containing the (label, content, line_number) of the block.
    block_vars : dict
        Dict of block variables.
    gallery_conf : dict
        Contains the configuration of Sphinx-Gallery

    Returns
    -------
    rst : str
        The ReSTructuredText that will be rendered to HTML containing
        the images. This is often produced by :func:`figure_rst`.
    """
    image_path_iterator = block_vars['image_path_iterator']
    image_paths = list()
    e = mlab.get_engine()
    for scene, image_path in zip(e.scenes, image_path_iterator):
        try:
            mlab.savefig(image_path, figure=scene)
        except Exception:
            mlab.close(all=True)
            raise
        # make sure the image is not too large
        scale_image(image_path, image_path, 850, 999)
        if 'images' in gallery_conf['compress_images']:

# Path: sphinx_gallery/utils.py
# def scale_image(in_fname, out_fname, max_width, max_height):
#     """Scales an image with the same aspect ratio centered in an
#        image box with the given max_width and max_height
#        if in_fname == out_fname the image can only be scaled down
#     """
#     # local import to avoid testing dependency on PIL:
#     Image = _get_image()
#     img = Image.open(in_fname)
#     # XXX someday we should just try img.thumbnail((max_width, max_height)) ...
#     width_in, height_in = img.size
#     scale_w = max_width / float(width_in)
#     scale_h = max_height / float(height_in)
# 
#     if height_in * scale_w <= max_height:
#         scale = scale_w
#     else:
#         scale = scale_h
# 
#     if scale >= 1.0 and in_fname == out_fname:
#         return
# 
#     width_sc = int(round(scale * width_in))
#     height_sc = int(round(scale * height_in))
# 
#     # resize the image using resize; if using .thumbnail and the image is
#     # already smaller than max_width, max_height, then this won't scale up
#     # at all (maybe could be an option someday...)
#     img = img.resize((width_sc, height_sc), Image.BICUBIC)
#     # img.thumbnail((width_sc, height_sc), Image.BICUBIC)
#     # width_sc, height_sc = img.size  # necessary if using thumbnail
# 
#     # insert centered
#     thumb = Image.new('RGBA', (max_width, max_height), (255, 255, 255, 0))
#     pos_insert = ((max_width - width_sc) // 2, (max_height - height_sc) // 2)
#     thumb.paste(img, pos_insert)
# 
#     try:
#         thumb.save(out_fname)
#     except IOError:
#         # try again, without the alpha channel (e.g., for JPEG)
#         thumb.convert('RGB').save(out_fname)
# 
# def optipng(fname, args=()):
#     """Optimize a PNG in place.
# 
#     Parameters
#     ----------
#     fname : str
#         The filename. If it ends with '.png', ``optipng -o7 fname`` will
#         be run. If it fails because the ``optipng`` executable is not found
#         or optipng fails, the function returns.
#     args : tuple
#         Extra command-line arguments, such as ``['-o7']``.
#     """
#     if fname.endswith('.png'):
#         # -o7 because this is what CPython used
#         # https://github.com/python/cpython/pull/8032
#         try:
#             subprocess.check_call(
#                 ['optipng'] + list(args) + [fname],
#                 stdout=subprocess.PIPE,
#                 stderr=subprocess.PIPE)
#         except (subprocess.CalledProcessError, IOError):  # FileNotFoundError
#             pass


# Path: sphinx_gallery/scrapers.py
import importlib
import inspect
import os
import sys
import re
    import matplotlib
    import matplotlib.pyplot as plt
from textwrap import indent
from pathlib import PurePosixPath
from warnings import filterwarnings
from sphinx.errors import ExtensionError
from .utils import scale_image, optipng
    from matplotlib.animation import Animation
    from matplotlib.animation import FFMpegWriter, ImageMagickWriter
    from mayavi import mlab

def mayavi_scraper(block, block_vars, gallery_conf):
    """Scrape Mayavi images.

    Parameters
    ----------
    block : tuple
        A tuple containing the (label, content, line_number) of the block.
    block_vars : dict
        Dict of block variables.
    gallery_conf : dict
        Contains the configuration of Sphinx-Gallery

    Returns
    -------
    rst : str
        The ReSTructuredText that will be rendered to HTML containing
        the images. This is often produced by :func:`figure_rst`.
    """
    image_path_iterator = block_vars['image_path_iterator']
    image_paths = list()
    e = mlab.get_engine()
    for scene, image_path in zip(e.scenes, image_path_iterator):
        try:
            mlab.savefig(image_path, figure=scene)
        except Exception:
            mlab.close(all=True)
            raise
        # make sure the image is not too large
        scale_image(image_path, image_path, 850, 999)
        if 'images' in gallery_conf['compress_images']:

            optipng(image_path, gallery_conf['compress_images_args'])