Skip to content

Commit

Permalink
autopep8
Browse files Browse the repository at this point in the history
  • Loading branch information
thet committed Jun 8, 2014
1 parent b345cd6 commit 8cd378a
Show file tree
Hide file tree
Showing 6 changed files with 124 additions and 111 deletions.
102 changes: 58 additions & 44 deletions plone/scale/scale.py
Expand Up @@ -9,7 +9,7 @@


def scaleImage(image, width=None, height=None, direction="down",
quality=88, result=None):
quality=88, result=None):
"""Scale the given image data to another size and return the result
as a string or optionally write in to the file-like `result` object.
Expand Down Expand Up @@ -39,11 +39,21 @@ def scaleImage(image, width=None, height=None, direction="down",
image = scalePILImage(image, width, height, direction)

if result is None:
result=StringIO()
image.save(result, format, quality=quality, optimize=True, progressive=True)
result=result.getvalue()
result = StringIO()
image.save(
result,
format,
quality=quality,
optimize=True,
progressive=True)
result = result.getvalue()
else:
image.save(result, format, quality=quality, optimize=True, progressive=True)
image.save(
result,
format,
quality=quality,
optimize=True,
progressive=True)
result.seek(0)

return result, format, image.size
Expand All @@ -57,7 +67,7 @@ def scalePILImage(image, width=None, height=None, direction="down"):
not lost, which JPEG does not support.
Three different scaling options are supported:
* `up` scaling scales the smallest dimension up to the required size
and scrops the other dimension if needed.
* `down` scaling starts by scaling the largest dimension to the required
Expand All @@ -72,75 +82,79 @@ def scalePILImage(image, width=None, height=None, direction="down"):
The return value the scaled image in the form of another instance of
`PIL.Image`.
"""
if direction=="keep":
direction="thumbnail"
if direction == "keep":
direction = "thumbnail"

if direction=="thumbnail" and not (width and height):
raise ValueError("Thumbnailing requires both width and height to be specified")
if direction == "thumbnail" and not (width and height):
raise ValueError(
"Thumbnailing requires both width and height to be specified")
elif width is None and height is None:
raise ValueError("Either width or height need to be given")

if image.mode=="1":
if image.mode == "1":
# Convert black&white to grayscale
image=image.convert("L")
elif image.mode=="P":
image = image.convert("L")
elif image.mode == "P":
# Convert palette based images to 3x8bit+alpha
image=image.convert("RGBA")
elif image.mode=="CMYK":
image = image.convert("RGBA")
elif image.mode == "CMYK":
# Convert CMYK to RGB, allowing for web previews of print images
image=image.convert("RGB")
image = image.convert("RGB")

current_size=image.size
current_size = image.size
# Determine scale factor needed to get the right height
if height is None:
scale_height=None
scale_height = None
else:
scale_height=(float(height)/float(current_size[1]))
scale_height = (float(height) / float(current_size[1]))
if width is None:
scale_width=None
scale_width = None
else:
scale_width=(float(width)/float(current_size[0]))
scale_width = (float(width) / float(current_size[0]))

if scale_height==scale_width or direction=="thumbnail":
if scale_height == scale_width or direction == "thumbnail":
# The original already has the right aspect ratio, so we only need
# to scale.
image.thumbnail((width, height), PIL.Image.ANTIALIAS)
else:
if direction=="down":
if scale_height is None or (scale_width is not None and scale_width>scale_height):
if direction == "down":
if scale_height is None or (
scale_width is not None and scale_width > scale_height):
# Width is the smallest dimension (relatively), so scale up
# to the desired width
new_width=width
new_height=int(round(current_size[1]*scale_width))
new_width = width
new_height = int(round(current_size[1] * scale_width))
else:
new_height=height
new_width=int(round(current_size[0]*scale_height))
new_height = height
new_width = int(round(current_size[0] * scale_height))
else:
if scale_height is None or (scale_width is not None and scale_width<scale_height):
if scale_height is None or (
scale_width is not None and scale_width < scale_height):
# Width is the largest dimension (relatively), so scale up
# to the desired width
new_width=width
new_height=int(round(current_size[1]*scale_width))
new_width = width
new_height = int(round(current_size[1] * scale_width))
else:
new_height=height
new_width=int(round(current_size[0]*scale_height))
new_height = height
new_width = int(round(current_size[0] * scale_height))

image.draft(image.mode, (new_width, new_height))
image=image.resize((new_width, new_height), PIL.Image.ANTIALIAS)
image = image.resize((new_width, new_height), PIL.Image.ANTIALIAS)

if (width is not None and new_width>width) or (height is not None and new_height>height):
if (width is not None and new_width > width) or (
height is not None and new_height > height):
if width is None:
left=0
right=new_width
left = 0
right = new_width
else:
left=int((new_width-width)/2.0)
right=left+width
left = int((new_width - width) / 2.0)
right = left + width
if height is None:
top=0
bottom=new_height
top = 0
bottom = new_height
else:
top=int((new_height-height)/2.0)
bottom=top+height
image=image.crop((left, top, right, bottom))
top = int((new_height - height) / 2.0)
bottom = top + height
image = image.crop((left, top, right, bottom))

return image
10 changes: 5 additions & 5 deletions plone/scale/storage.py
Expand Up @@ -50,12 +50,12 @@ def __repr__(self):
name = self.__class__.__name__
return '<%s context=%r>' % (name, self.context)

__str__=__repr__
__str__ = __repr__

@property
def storage(self):
return IAnnotations(self.context).setdefault('plone.scale',
PersistentDict())
PersistentDict())

def hash(self, **parameters):
return tuple(sorted(parameters.items()))
Expand All @@ -79,8 +79,8 @@ def scale(self, factory=None, **parameters):
width, height = dimensions
uid = str(uuid4())
info = dict(uid=uid, data=data, width=width, height=height,
mimetype='image/%s' % format.lower(), key=key,
modified=modified)
mimetype='image/%s' % format.lower(), key=key,
modified=modified)
storage[key] = storage[uid] = info
return info

Expand All @@ -104,7 +104,7 @@ def keys(self):
return self.storage.keys()

def has_key(self, uid):
return self.storage.has_key(uid)
return uid in self.storage

__contains__ = has_key

Expand Down
1 change: 0 additions & 1 deletion plone/scale/tests/__init__.py
@@ -1,4 +1,3 @@
import os.path

TEST_DATA_LOCATION = os.path.join(os.path.dirname(__file__), "data")

47 changes: 23 additions & 24 deletions plone/scale/tests/test_scale.py
@@ -1,77 +1,76 @@
from cStringIO import StringIO
import os.path
from unittest import TestCase
from plone.scale.scale import scaleImage
from plone.scale.tests import TEST_DATA_LOCATION
from unittest import TestCase
import PIL.Image
import os.path

PNG = open(os.path.join(TEST_DATA_LOCATION, "logo.png")).read()
GIF = open(os.path.join(TEST_DATA_LOCATION, "logo.gif")).read()
CMYK = open(os.path.join(TEST_DATA_LOCATION, "cmyk.jpg")).read()


class ScalingTests(TestCase):

def testNewSizeReturned(self):
(imagedata, format, size)=scaleImage(PNG, 42, 51, "down")
input=StringIO(imagedata)
image=PIL.Image.open(input)
(imagedata, format, size) = scaleImage(PNG, 42, 51, "down")
input = StringIO(imagedata)
image = PIL.Image.open(input)
self.assertEqual(image.size, size)

def testScaledImageIsJpeg(self):
self.assertEqual(scaleImage(GIF, 84, 103, "down")[1] , "JPEG")
self.assertEqual(scaleImage(GIF, 84, 103, "down")[1], "JPEG")

def testScaledCMYKIsRGB(self):
(imagedata, format, size)=scaleImage(CMYK, 42, 51, "down")
input=StringIO(imagedata)
image=PIL.Image.open(input)
(imagedata, format, size) = scaleImage(CMYK, 42, 51, "down")
input = StringIO(imagedata)
image = PIL.Image.open(input)
self.assertEqual(image.mode, "RGB")

def XtestScaledPngImageIsPng(self):
# This test failes because the sample input file has a format of
# None according to PIL..
self.assertEqual(scaleImage(PNG, 84, 103, "down")[1] , "PNG")

self.assertEqual(scaleImage(PNG, 84, 103, "down")[1], "PNG")

def testSameSizeDownScale(self):
self.assertEqual(scaleImage(PNG, 84, 103, "down")[2], (84, 103))
self.assertEqual(scaleImage(PNG, 84, 103, "down")[2], (84, 103))

def testHalfSizeDownScale(self):
self.assertEqual(scaleImage(PNG, 42, 51, "down")[2], (42, 51))
self.assertEqual(scaleImage(PNG, 42, 51, "down")[2], (42, 51))

def testScaleWithCropDownScale(self):
self.assertEqual(scaleImage(PNG, 20, 51, "down")[2], (20, 51))
self.assertEqual(scaleImage(PNG, 20, 51, "down")[2], (20, 51))

def testNoStretchingDownScale(self):
self.assertEqual(scaleImage(PNG, 200, 103, "down")[2], (200, 103))
self.assertEqual(scaleImage(PNG, 200, 103, "down")[2], (200, 103))

def testRestrictWidthOnlyDownScale(self):
self.assertEqual(scaleImage(PNG, 42, None, "down")[2], (42, 52))
self.assertEqual(scaleImage(PNG, 42, None, "down")[2], (42, 52))

def testRestrictHeightOnlyDownScale(self):
self.assertEqual(scaleImage(PNG, None, 51, "down")[2], (42, 51))

self.assertEqual(scaleImage(PNG, None, 51, "down")[2], (42, 51))

def testSameSizeUpScale(self):
self.assertEqual(scaleImage(PNG, 84, 103, "up")[2], (84, 103))
self.assertEqual(scaleImage(PNG, 84, 103, "up")[2], (84, 103))

def testHalfSizeUpScale(self):
self.assertEqual(scaleImage(PNG, 42, 51, "up")[2], (42, 51))
self.assertEqual(scaleImage(PNG, 42, 51, "up")[2], (42, 51))

def testNoStretchingUpScale(self):
self.assertEqual(scaleImage(PNG, 200, 103, "up")[2], (84, 103))
self.assertEqual(scaleImage(PNG, 200, 103, "up")[2], (84, 103))

def testRestrictWidthOnlyUpScale(self):
self.assertEqual(scaleImage(PNG, 42, None, "up")[2], (42, 52))
self.assertEqual(scaleImage(PNG, 42, None, "up")[2], (42, 52))

def testRestrictHeightOnlyUpScale(self):
self.assertEqual(scaleImage(PNG, None, 51, "up")[2], (42, 51))
self.assertEqual(scaleImage(PNG, None, 51, "up")[2], (42, 51))

def testNoRestrictions(self):
self.assertRaises(ValueError, scaleImage, PNG, None, None)

def testKeepAspectRatio(self):
self.assertEqual(scaleImage(PNG, 80, 80, "keep")[2], (65, 80))


def testQuality(self):
img1 = scaleImage(CMYK, 84, 103)[0]
img2 = scaleImage(CMYK, 84, 103, quality=50)[0]
Expand Down
6 changes: 3 additions & 3 deletions plone/scale/tests/test_storage.py
@@ -1,5 +1,5 @@
from unittest import TestCase
from operator import itemgetter, setitem, delitem
from unittest import TestCase


class AnnotationStorageTests(TestCase):
Expand Down Expand Up @@ -87,12 +87,12 @@ def testKeys(self):

def testNegativeHasKey(self):
storage = self.storage
self.assertEqual(storage.has_key('one'), False)
self.assertEqual('one' in storage, False)

def testPositiveHasKey(self):
storage = self.storage
storage.storage.update(one=None)
self.assertEqual(storage.has_key('one'), True)
self.assertEqual('one' in storage, True)

def testDeleteNonExistingItem(self):
storage = self.storage
Expand Down
69 changes: 35 additions & 34 deletions setup.py
Expand Up @@ -28,37 +28,38 @@
# uuid is only required before Python 2.5
STORAGE_REQUIREMENTS.append("uuid")

setup(name="plone.scale",
version=version,
description="Image scaling",
long_description=readme + "\n" + changes,
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Plone",
"Framework :: Zope2",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
],
keywords="image scaling",
author='Plone Foundation',
author_email='plone-developers@lists.sourceforge.net',
url='http://pypi.python.org/pypi/plone.scale',
license="BSD",
packages=find_packages(exclude=["ez_setup"]),
namespace_packages=["plone"],
include_package_data=True,
zip_safe=True,
test_suite="plone.scale",
install_requires=[
# We can't actually depend on PIL because not everyone can install it
# as an egg.
#"PIL",
"setuptools",
],
extras_require = dict(
storage = STORAGE_REQUIREMENTS,
sphinx = STORAGE_REQUIREMENTS + SPHINX_REQUIREMENTS,
),
)
setup(
name="plone.scale",
version=version,
description="Image scaling",
long_description=readme + "\n" + changes,
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Plone",
"Framework :: Zope2",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
],
keywords="image scaling",
author='Plone Foundation',
author_email='plone-developers@lists.sourceforge.net',
url='http://pypi.python.org/pypi/plone.scale',
license="BSD",
packages=find_packages(exclude=["ez_setup"]),
namespace_packages=["plone"],
include_package_data=True,
zip_safe=True,
test_suite="plone.scale",
install_requires=[
# We can't actually depend on PIL because not everyone can install it
# as an egg.
# "PIL",
"setuptools",
],
extras_require=dict(
storage=STORAGE_REQUIREMENTS,
sphinx=STORAGE_REQUIREMENTS + SPHINX_REQUIREMENTS,
),
)

0 comments on commit 8cd378a

Please sign in to comment.