PillowImage.utils   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 58
Duplicated Lines 87.93 %

Importance

Changes 0
Metric Value
wmc 11
eloc 31
dl 51
loc 58
rs 10
c 0
b 0
f 0

1 Function

Rating   Name   Duplication   Size   Complexity  
C img_adjust() 51 51 11

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
import os
2
from tempfile import NamedTemporaryFile
3
4
from PIL import Image, ImageEnhance
5
6
7 View Code Duplication
def img_adjust(image, opacity=1.0, rotate=None, fit=0, tempdir=None, bw=False):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
8
    """
9
    Reduce the opacity of a PNG image or add rotation.
10
11
    Inspiration: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
12
13
    :param image: PNG image file
14
    :param opacity: float representing opacity percentage
15
    :param rotate: Degrees to rotate
16
    :param fit: If true, expands the size of the image to fit the whole canvas
17
    :param tempdir: Temporary directory
18
    :param bw: Set image to black and white
19
    :return:  Path to modified PNG
20
    """
21
    # Validate parameters
22
    if opacity:
23
        try:
24
            assert 0 <= opacity <= 1
25
        except AssertionError:
26
            return image
27
    assert os.path.isfile(image), 'Image is not a file'
28
29
    # Open image in RGBA mode if not already in RGBA
30
    with Image.open(image) as im:
31
        if im.mode != 'RGBA':
32
            im = im.convert('RGBA')
33
        else:
34
            im = im.copy()
35
36
        if rotate:
37
            # Rotate the image
38
            if rotate == 90:
39
                im = im.transpose(Image.ROTATE_90)
40
            elif rotate == 180:
41
                im = im.transpose(Image.ROTATE_180)
42
            elif rotate == 270:
43
                im = im.transpose(Image.ROTATE_270)
44
            else:
45
                im = im.rotate(rotate, expand=fit)
46
47
        # Adjust opacity
48
        alpha = im.split()[3]
49
        alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
50
        im.putalpha(alpha)
51
        if bw:
52
            im.convert('L')
53
54
        # Save modified image file
55
        with NamedTemporaryFile(suffix='.png', dir=tempdir, delete=False) as dst:
56
            im.save(dst)
57
            return dst.name
58