def test_check(self): # Check the correctness of the convenience function for module in features.modules: self.assertEqual(features.check_module(module), features.check(module)) for codec in features.codecs: self.assertEqual(features.check_codec(codec), features.check(codec)) for feature in features.features: self.assertEqual(features.check_feature(feature), features.check(feature))
# -*- coding: utf-8 -*- from helper import unittest, PillowTestCase from PIL import Image, ImageDraw, ImageFont, features FONT_SIZE = 20 FONT_PATH = "Tests/fonts/DejaVuSans.ttf" @unittest.skipUnless(features.check('raqm'), "Raqm Library is not installed.") class TestImagecomplextext(PillowTestCase): def test_english(self): # smoke test, this should not fail ttf = ImageFont.truetype(FONT_PATH, FONT_SIZE) im = Image.new(mode='RGB', size=(300, 100)) draw = ImageDraw.Draw(im) draw.text((0, 0), 'TEST', font=ttf, fill=500, direction='ltr') def test_complex_text(self): ttf = ImageFont.truetype(FONT_PATH, FONT_SIZE) im = Image.new(mode='RGB', size=(300, 100)) draw = ImageDraw.Draw(im) draw.text((0, 0), 'اهلا عمان', font=ttf, fill=500) target = 'Tests/images/test_text.png' target_img = Image.open(target) self.assert_image_similar(im, target_img, .5)
print("-"*68) for name, feature in [ ("pil", "PIL CORE"), ("tkinter", "TKINTER"), ("freetype2", "FREETYPE2"), ("littlecms2", "LITTLECMS2"), ("webp", "WEBP"), ("transp_webp", "Transparent WEBP"), ("webp_mux", "WEBPMUX"), ("jpg", "JPEG"), ("jpg_2000", "OPENJPEG (JPEG2000)"), ("zlib", "ZLIB (PNG/ZIP)"), ("libtiff", "LIBTIFF"), ("raqm", "RAQM (Bidirectional Text)") ]: if features.check(name): print("---", feature, "support ok") else: print("***", feature, "support not installed") print("-"*68) # use doctest to make sure the test program behaves as documented! import doctest print("Running selftest:") status = doctest.testmod(sys.modules[__name__]) if status[0]: print("*** %s tests of %d failed." % status) exit_status = 1 else: print("--- %s tests passed." % status[1])
def test_webp_mux(self): self.assertEqual(features.check('webp_mux'), _webp.HAVE_WEBPMUX)
import re import shutil import sys import unittest from io import BytesIO from PIL import Image, ImageDraw, ImageFont, features from .helper import PillowTestCase, is_pypy, is_win32 FONT_PATH = "Tests/fonts/FreeMono.ttf" FONT_SIZE = 20 TEST_TEXT = "hey you\nyou are awesome\nthis looks awkward" HAS_FREETYPE = features.check("freetype2") HAS_RAQM = features.check("raqm") class SimplePatcher: def __init__(self, parent_obj, attr_name, value): self._parent_obj = parent_obj self._attr_name = attr_name self._saved = None self._is_saved = False self._value = value def __enter__(self): # Patch the attr on the object if hasattr(self._parent_obj, self._attr_name): self._saved = getattr(self._parent_obj, self._attr_name)
# -*- coding: utf-8 -*- from helper import unittest, PillowTestCase from PIL import Image, ImageDraw, ImageFont, features from io import BytesIO import os import sys import copy FONT_PATH = "Tests/fonts/FreeMono.ttf" FONT_SIZE = 20 TEST_TEXT = "hey you\nyou are awesome\nthis looks awkward" HAS_FREETYPE = features.check('freetype2') HAS_RAQM = features.check('raqm') class SimplePatcher(object): def __init__(self, parent_obj, attr_name, value): self._parent_obj = parent_obj self._attr_name = attr_name self._saved = None self._is_saved = False self._value = value def __enter__(self): # Patch the attr on the object if hasattr(self._parent_obj, self._attr_name): self._saved = getattr(self._parent_obj, self._attr_name) setattr(self._parent_obj, self._attr_name, self._value)
from helper import unittest, PillowLeakTestCase from PIL import Image, features from io import BytesIO test_file = "Tests/images/hopper.webp" @unittest.skipUnless(features.check('webp'), "WebP is not installed") class TestWebPLeaks(PillowLeakTestCase): mem_limit = 3 * 1024 # kb iterations = 100 def test_leak_load(self): with open(test_file, 'rb') as f: im_data = f.read() def core(): with Image.open(BytesIO(im_data)) as im: im.load() self._test_leak(core) if __name__ == '__main__': unittest.main()
print("-" * 68) print("Pillow", Image.__version__, "TEST SUMMARY ") print("-" * 68) print("Python modules loaded from", os.path.dirname(Image.__file__)) print("Binary modules loaded from", os.path.dirname(Image.core.__file__)) print("-" * 68) for name, feature in [("pil", "PIL CORE"), ("tkinter", "TKINTER"), ("freetype2", "FREETYPE2"), ("littlecms2", "LITTLECMS2"), ("webp", "WEBP"), ("transp_webp", "WEBP Transparency"), ("webp_mux", "WEBPMUX"), ("webp_anim", "WEBP Animation"), ("jpg", "JPEG"), ("jpg_2000", "OPENJPEG (JPEG2000)"), ("zlib", "ZLIB (PNG/ZIP)"), ("libtiff", "LIBTIFF"), ("raqm", "RAQM (Bidirectional Text)")]: if features.check(name): print("---", feature, "support ok") else: print("***", feature, "support not installed") print("-" * 68) # use doctest to make sure the test program behaves as documented! import doctest print("Running selftest:") status = doctest.testmod(sys.modules[__name__]) if status[0]: print("*** %s tests of %d failed." % status) exit_status = 1 else: print("--- %s tests passed." % status[1])
def test_webp_anim(): assert features.check("webp_anim") == _webp.HAVE_WEBPANIM
def test_check_warns_on_nonexistent(): with pytest.warns(UserWarning) as cm: has_feature = features.check("typo") assert has_feature is False assert str(cm[-1].message) == "Unknown feature 'typo'."
def test_webp_mux(): assert features.check("webp_mux") == _webp.HAVE_WEBPMUX
def test_webp_transparency(): assert features.check("transp_webp") != _webp.WebPDecoderBuggyAlpha() assert features.check("transp_webp") == _webp.HAVE_TRANSPARENCY
from django.core.files import File from django.core.files.base import ContentFile from django.core.files.move import file_move_safe from django.core.files.temp import NamedTemporaryFile from django.core.files.uploadedfile import ( InMemoryUploadedFile, SimpleUploadedFile, TemporaryUploadedFile, UploadedFile, ) from django.test import override_settings try: from PIL import Image, features HAS_WEBP = features.check('webp') except ImportError: Image = None HAS_WEBP = False else: from django.core.files import images class FileTests(unittest.TestCase): def test_unicode_uploadedfile_name(self): uf = UploadedFile(name='¿Cómo?', content_type='text') self.assertIs(type(repr(uf)), str) def test_unicode_file_name(self): f = File(None, 'djángö') self.assertIs(type(repr(f)), str)
from PIL import Image, ImageDraw, ImageFont, features from io import BytesIO import os import sys import copy import re import shutil import distutils.version FONT_PATH = "Tests/fonts/FreeMono.ttf" FONT_SIZE = 20 TEST_TEXT = "hey you\nyou are awesome\nthis looks awkward" HAS_FREETYPE = features.check('freetype2') HAS_RAQM = features.check('raqm') class SimplePatcher(object): def __init__(self, parent_obj, attr_name, value): self._parent_obj = parent_obj self._attr_name = attr_name self._saved = None self._is_saved = False self._value = value def __enter__(self): # Patch the attr on the object if hasattr(self._parent_obj, self._attr_name): self._saved = getattr(self._parent_obj, self._attr_name)
from .helper import unittest, PillowTestCase, hopper from PIL import Image, ImagePalette, features try: from PIL import MicImagePlugin except ImportError: olefile_installed = False else: olefile_installed = True TEST_FILE = "Tests/images/hopper.mic" @unittest.skipUnless(olefile_installed, "olefile package not installed") @unittest.skipUnless(features.check('libtiff'), "libtiff not installed") class TestFileMic(PillowTestCase): def test_sanity(self): im = Image.open(TEST_FILE) im.load() self.assertEqual(im.mode, "RGBA") self.assertEqual(im.size, (128, 128)) self.assertEqual(im.format, "MIC") # Adjust for the gamma of 2.2 encoded into the file lut = ImagePalette.make_gamma_lut(1/2.2) im = Image.merge('RGBA', [chan.point(lut) for chan in im.split()]) im2 = hopper("RGBA") self.assert_image_similar(im, im2, 10)
import matplotlib.pyplot as plt import itertools import matplotlib as mpl import seaborn as sns sns.set(style="whitegrid") # %% avg_df=df[df['class'] == 'weighted avg'] f1_df=df[df['score_type'] == 'f1-score'] # %% #fm = mpl.font_manager #fm._fmcache from PIL import features from PIL import TiffImagePlugin print(features.check('libtiff')) #TiffImagePlugin.WRITE_LIBTIFF = True # %% # Say, "the default sans-serif font is COMIC SANS" mpl.rcParams['font.sans-serif'] = "Arial" # Then, "ALWAYS use sans-serif fonts" mpl.rcParams['font.family'] = "sans-serif" # %% ##figure 4 fig, ax = plt.subplots() ax.yaxis.grid(True) #fig.set_size_inches(18, 15) fig.set_size_inches(4, 4)
def test_webp_mux(self): self.assertEqual(features.check("webp_mux"), _webp.HAVE_WEBPMUX)
from PIL import Image, ImageDraw, ImageFont, features print(features.check('raqm')) print(Image.__version__) img = Image.new('RGB', (800, 300), color=(73, 109, 137)) d = ImageDraw.Draw(img) fnt = ImageFont.truetype( '/usr/share/fonts/truetype/noto/NotoSansTibetan-Regular.ttf', 24, layout_engine=ImageFont.LAYOUT_BASIC) d.text((10, 10), "༄༅། །སྒྲུབ།", font=fnt, fill=(255, 255, 0)) img.save('result.png') fnt = ImageFont.truetype('NotoSansTibetan-Regular.ttf', 24, layout_engine=ImageFont.LAYOUT_RAQM) print("things work until...") res = fnt.getmask("༄༅། །སྒྲུབ།", features=[ 'ccmp', 'abvs', 'blws', 'calt', 'liga', 'kern', 'abvm', 'blwm', 'mkmk' ])
def test_webp_anim(self): self.assertEqual(features.check("webp_anim"), _webp.HAVE_WEBPANIM)
def skip_unless_feature(feature): reason = f"{feature} not available" return pytest.mark.skipif(not features.check(feature), reason=reason)
from helper import unittest, PillowLeakTestCase from PIL import Image, features from io import BytesIO test_file = "Tests/images/hopper.webp" @unittest.skipUnless(features.check('webp'), "WebP is not installed") class TestWebPLeaks(PillowLeakTestCase): mem_limit = 3 * 1024 # kb iterations = 100 def test_leak_load(self): with open(test_file, 'rb') as f: im_data = f.read() def core(): with Image.open(BytesIO(im_data)) as im: im.load() self._test_leak(core) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- from .helper import unittest, PillowTestCase from PIL import Image, ImageDraw, ImageFont, features FONT_SIZE = 20 FONT_PATH = "Tests/fonts/DejaVuSans.ttf" @unittest.skipUnless(features.check('raqm'), "Raqm Library is not installed.") class TestImagecomplextext(PillowTestCase): def test_english(self): # smoke test, this should not fail ttf = ImageFont.truetype(FONT_PATH, FONT_SIZE) im = Image.new(mode='RGB', size=(300, 100)) draw = ImageDraw.Draw(im) draw.text((0, 0), 'TEST', font=ttf, fill=500, direction='ltr') def test_complex_text(self): ttf = ImageFont.truetype(FONT_PATH, FONT_SIZE) im = Image.new(mode='RGB', size=(300, 100)) draw = ImageDraw.Draw(im) draw.text((0, 0), 'اهلا عمان', font=ttf, fill=500) target = 'Tests/images/test_text.png' target_img = Image.open(target) self.assert_image_similar(im, target_img, .5) def test_y_offset(self): ttf = ImageFont.truetype("Tests/fonts/NotoNastaliqUrdu-Regular.ttf",
def read(self, extension=None, quality=None): # NOQA # returns image buffer in byte format. img_buffer = BytesIO() requested_extension = extension or self.extension # 1 and P mode images will be much smaller if converted back to # their original mode. So let's do that after resizing. Get $$. if (self.context.config.PILLOW_PRESERVE_INDEXED_MODE and requested_extension in [None, ".png", ".gif"] and self.original_mode in ["P", "1"] and self.original_mode != self.image.mode): if self.original_mode == "1": self.image = self.image.convert("1") else: # libimagequant might not be enabled on compile time # but it's better than default octree for RGBA images quantize_method = Image.LIBIMAGEQUANT if pillow_features.check( "libimagequant") else None self.image = self.image.quantize(method=quantize_method) ext = requested_extension or self.get_default_extension() options = {"quality": quality} if ext in (".jpg", ".jpeg"): options["optimize"] = True if self.context.config.PROGRESSIVE_JPEG: # Can't simply set options['progressive'] to the value # of self.context.config.PROGRESSIVE_JPEG because save # operates on the presence of the key in **options, not # the value of that setting. options["progressive"] = True if self.image.mode != "RGB": self.image = self.image.convert("RGB") else: subsampling_config = self.context.config.PILLOW_JPEG_SUBSAMPLING qtables_config = self.context.config.PILLOW_JPEG_QTABLES if subsampling_config is not None or qtables_config is not None: # can't use 'keep' here as Pillow would try to extract # qtables/subsampling and fail options["quality"] = 0 orig_subsampling = self.subsampling orig_qtables = self.qtables if (subsampling_config == "keep" or subsampling_config is None) and (orig_subsampling is not None): options["subsampling"] = orig_subsampling else: options["subsampling"] = subsampling_config if (qtables_config == "keep" or qtables_config is None ) and (orig_qtables and 2 <= len(orig_qtables) <= 4): options["qtables"] = orig_qtables else: options["qtables"] = qtables_config if ext == ".png" and self.context.config.PNG_COMPRESSION_LEVEL is not None: options[ "compress_level"] = self.context.config.PNG_COMPRESSION_LEVEL if options["quality"] is None: options["quality"] = self.context.config.QUALITY if self.icc_profile is not None: options["icc_profile"] = self.icc_profile if self.context.config.PRESERVE_EXIF_INFO: if self.exif is not None: options["exif"] = self.exif try: if ext == ".webp": if options["quality"] == 100: logger.debug("webp quality is 100, using lossless instead") options["lossless"] = True options.pop("quality") if self.image.mode not in ["RGB", "RGBA"]: if self.image.mode == "P": mode = "RGBA" else: mode = "RGBA" if self.image.mode[-1] == "A" else "RGB" self.image = self.image.convert(mode) if ext in [".png", ".gif"] and self.image.mode == "CMYK": self.image = self.image.convert("RGBA") self.image.format = FORMATS.get( ext, FORMATS[self.get_default_extension()]) self.image.save(img_buffer, self.image.format, **options) except IOError: logger.exception( "Could not save as improved image, consider to increase ImageFile.MAXBLOCK" ) self.image.save(img_buffer, FORMATS[ext]) results = img_buffer.getvalue() img_buffer.close() self.extension = ext return results
def test_webp_transparency(self): self.assertEqual(features.check('transp_webp'), not _webp.WebPDecoderBuggyAlpha()) self.assertEqual(features.check('transp_webp'), _webp.HAVE_TRANSPARENCY)
def setUp(self): if not features.check("libtiff"): self.skipTest("tiff support not available")
def test_webp_anim(self): self.assertEqual(features.check('webp_anim'), _webp.HAVE_WEBPANIM)
X0 = int(W / 4) X1 = int(X0 * 3) Y0 = int(H / 4) Y1 = int(X0 * 3) # Two kinds of bounding box BBOX1 = [(X0, Y0), (X1, Y1)] BBOX2 = [X0, Y0, X1, Y1] # Two kinds of coordinate sequences POINTS1 = [(10, 10), (20, 40), (30, 30)] POINTS2 = [10, 10, 20, 40, 30, 30] KITE_POINTS = [(10, 50), (70, 10), (90, 50), (70, 90), (10, 50)] HAS_FREETYPE = features.check("freetype2") class TestImageDraw(PillowTestCase): def test_sanity(self): im = hopper("RGB").copy() draw = ImageDraw.ImageDraw(im) draw = ImageDraw.Draw(im) draw.ellipse(list(range(4))) draw.line(list(range(10))) draw.polygon(list(range(100))) draw.rectangle(list(range(4))) def test_valueerror(self):
def setUp(self): if not features.check('libtiff'): self.skipTest("tiff support not available")
def check_webp_transparency(self): self.assertEqual(features.check('transp_webp'), not _webp.WebPDecoderBuggyAlpha()) self.assertEqual(features.check('transp_webp'), _webp.HAVE_TRANSPARENCY)
from .helper import unittest, PillowTestCase, hopper from PIL import Image, ImagePalette, features try: from PIL import MicImagePlugin except ImportError: olefile_installed = False else: olefile_installed = True TEST_FILE = "Tests/images/hopper.mic" @unittest.skipUnless(olefile_installed, "olefile package not installed") @unittest.skipUnless(features.check('libtiff'), "libtiff not installed") class TestFileMic(PillowTestCase): def test_sanity(self): im = Image.open(TEST_FILE) im.load() self.assertEqual(im.mode, "RGBA") self.assertEqual(im.size, (128, 128)) self.assertEqual(im.format, "MIC") # Adjust for the gamma of 2.2 encoded into the file lut = ImagePalette.make_gamma_lut(1/2.2) im = Image.merge('RGBA', [chan.point(lut) for chan in im.split()]) im2 = hopper("RGBA") self.assert_image_similar(im, im2, 10)
def check_webp_mux(self): self.assertEqual(features.check('webp_mux'), _webp.HAVE_WEBPMUX)
X0 = int(W / 4) X1 = int(X0 * 3) Y0 = int(H / 4) Y1 = int(X0 * 3) # Two kinds of bounding box BBOX1 = [(X0, Y0), (X1, Y1)] BBOX2 = [X0, Y0, X1, Y1] # Two kinds of coordinate sequences POINTS1 = [(10, 10), (20, 40), (30, 30)] POINTS2 = [10, 10, 20, 40, 30, 30] KITE_POINTS = [(10, 50), (70, 10), (90, 50), (70, 90), (10, 50)] HAS_FREETYPE = features.check("freetype2") FONT_PATH = "Tests/fonts/FreeMono.ttf" class TestImageDraw(PillowTestCase): def test_sanity(self): im = hopper("RGB").copy() draw = ImageDraw2.Draw(im) pen = ImageDraw2.Pen("blue", width=7) draw.line(list(range(10)), pen) from PIL import ImageDraw draw, handler = ImageDraw.getdraw(im)
f"Can't load pillow: {e}\n" "Please follow next steps on wiki: " "https://github.com/fixator10/Fixator10-Cogs/wiki/" "Installing-Leveler#my-bot-throws-error-on-load-something-related-to-pillow." ) try: from PIL import Image LANCZOS = Image.Resampling.LANCZOS except AttributeError: from PIL.Image import LANCZOS log = getLogger("red.fixator10-cogs.leveler") AVATAR_FORMAT = "webp" if pil_features.check("webp_anim") else "jpg" log.debug(f"using {AVATAR_FORMAT} avatar format") class ImageGenerators(MixinMeta): """Image generators""" def make_rank_image( self, rank_background, rank_avatar, user, server, userinfo, exp_total, server_rank, bank_credits,