# Path: sphinx_gallery/utils.py
# def _get_image():
#     try:
#         from PIL import Image
#     except ImportError as exc:  # capture the error for the modern way
#         try:
#             import Image
#         except ImportError:
#             raise ExtensionError(
#                 'Could not import pillow, which is required '
#                 'to rescale images (e.g., for thumbnails): %s' % (exc,))
#     return Image
# 
# 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 _has_optipng():
#     try:
#         subprocess.check_call(['optipng', '--version'],
#                               stdout=subprocess.PIPE,
#                               stderr=subprocess.PIPE)
#     except IOError:  # FileNotFoundError
#         return False
#     else:
#         return True
# 
# def _has_pypandoc():
#     """Check if pypandoc package available."""
#     try:
#         import pypandoc  # noqa
#         # Import error raised only when function called
#         version = pypandoc.get_pandoc_version()
#     except (ImportError, OSError):
#         return None, None
#     else:
#         return True, version


import codecs
import os
import os.path as op
import re
import shutil
import sys
import time
import pytest
    import numpy as np
    import numpy as np
        import memory_profiler  # noqa, analysis:ignore
    import numpy as np
from io import StringIO
from sphinx.application import Sphinx
from sphinx.errors import ExtensionError
from sphinx.util.docutils import docutils_namespace
from sphinx_gallery.utils import (_get_image, scale_image, _has_optipng,
                                  _has_pypandoc)
    from numpy.testing import assert_allclose
    """Test sphinx_gallery_thumbnail_path."""
    # Make sure our thumbnail matches what it should be
    fname_orig = op.join(
        sphinx_app.srcdir, '_static_nonstandard', 'demo.png')
    fname_thumb = op.join(
        sphinx_app.outdir, '_images',
        'sphx_glr_plot_second_future_imports_thumb.png')
    fname_new = str(tmpdir.join('new.png'))
    scale_image(fname_orig, fname_new,
                *sphinx_app.config.sphinx_gallery_conf["thumbnail_size"])
    Image = _get_image()
    orig = np.asarray(Image.open(fname_thumb))
    new = np.asarray(Image.open(fname_new))
    assert new.shape[:2] == orig.shape[:2]
    assert new.shape[2] in (3, 4)  # optipng can strip the alpha channel
    corr = np.corrcoef(new[..., :3].ravel(), orig[..., :3].ravel())[0, 1]
    assert corr > 0.99


def test_negative_thumbnail_config(sphinx_app, tmpdir):
    """Test 'sphinx_gallery_thumbnail_number' config works correctly for
    negative numbers."""
    # Make sure our thumbnail is the 2nd (last) image
    fname_orig = op.join(
        sphinx_app.outdir, '_images',
        'sphx_glr_plot_matplotlib_alt_002.png')
    fname_thumb = op.join(
        sphinx_app.outdir, '_images',
        'sphx_glr_plot_matplotlib_alt_thumb.png')
    fname_new = str(tmpdir.join('new.png'))

# Path: sphinx_gallery/utils.py
# def _get_image():
#     try:
#         from PIL import Image
#     except ImportError as exc:  # capture the error for the modern way
#         try:
#             import Image
#         except ImportError:
#             raise ExtensionError(
#                 'Could not import pillow, which is required '
#                 'to rescale images (e.g., for thumbnails): %s' % (exc,))
#     return Image
# 
# 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 _has_optipng():
#     try:
#         subprocess.check_call(['optipng', '--version'],
#                               stdout=subprocess.PIPE,
#                               stderr=subprocess.PIPE)
#     except IOError:  # FileNotFoundError
#         return False
#     else:
#         return True
# 
# def _has_pypandoc():
#     """Check if pypandoc package available."""
#     try:
#         import pypandoc  # noqa
#         # Import error raised only when function called
#         version = pypandoc.get_pandoc_version()
#     except (ImportError, OSError):
#         return None, None
#     else:
#         return True, version


# Path: sphinx_gallery/tests/test_full.py
import codecs
import os
import os.path as op
import re
import shutil
import sys
import time
import pytest
    import numpy as np
    import numpy as np
        import memory_profiler  # noqa, analysis:ignore
    import numpy as np
from io import StringIO
from sphinx.application import Sphinx
from sphinx.errors import ExtensionError
from sphinx.util.docutils import docutils_namespace
from sphinx_gallery.utils import (_get_image, scale_image, _has_optipng,
                                  _has_pypandoc)
    from numpy.testing import assert_allclose

    """Test sphinx_gallery_thumbnail_path."""
    # Make sure our thumbnail matches what it should be
    fname_orig = op.join(
        sphinx_app.srcdir, '_static_nonstandard', 'demo.png')
    fname_thumb = op.join(
        sphinx_app.outdir, '_images',
        'sphx_glr_plot_second_future_imports_thumb.png')
    fname_new = str(tmpdir.join('new.png'))
    scale_image(fname_orig, fname_new,
                *sphinx_app.config.sphinx_gallery_conf["thumbnail_size"])
    Image = _get_image()
    orig = np.asarray(Image.open(fname_thumb))
    new = np.asarray(Image.open(fname_new))
    assert new.shape[:2] == orig.shape[:2]
    assert new.shape[2] in (3, 4)  # optipng can strip the alpha channel
    corr = np.corrcoef(new[..., :3].ravel(), orig[..., :3].ravel())[0, 1]
    assert corr > 0.99


def test_negative_thumbnail_config(sphinx_app, tmpdir):
    """Test 'sphinx_gallery_thumbnail_number' config works correctly for
    negative numbers."""
    # Make sure our thumbnail is the 2nd (last) image
    fname_orig = op.join(
        sphinx_app.outdir, '_images',
        'sphx_glr_plot_matplotlib_alt_002.png')
    fname_thumb = op.join(
        sphinx_app.outdir, '_images',
        'sphx_glr_plot_matplotlib_alt_thumb.png')
    fname_new = str(tmpdir.join('new.png'))

    scale_image(fname_orig, fname_new,