GithubHelp home page GithubHelp logo

python-resize-image's Introduction

python-resize-image v1.1.20 on PyPi MIT license Stable

A python package to easily resize images

This package provides function for easily resizing images.

Dependencies

  • Pillow 2.7++
  • Python 2.7/3.4

Introduction

The following functions are supported:

  • resize_crop crop the image with a centered rectangle of the specified size.
  • resize_cover resize the image to fill the specified area, crop as needed (same behavior as background-size: cover).
  • resize_contain resize the image so that it can fit in the specified area, keeping the ratio and without crop (same behavior as background-size: contain).
  • resize_height resize the image to the specified height adjusting width to keep the ratio the same.
  • resize_width resize the image to the specified width adjusting height to keep the ratio the same.
  • resize_thumbnail resize image while keeping the ratio trying its best to match the specified size.

Installation

Install python-resize-image using pip:

pip install python-resize-image

Usage

python-resize-image takes as first argument a PIL.Image and then size argument which can be a single integer or tuple of two integers.

In the following example, we open an image, crop it and save as new file:

from PIL import Image

from resizeimage import resizeimage


with open('test-image.jpeg', 'r+b') as f:
    with Image.open(f) as image:
        cover = resizeimage.resize_cover(image, [200, 100])
        cover.save('test-image-cover.jpeg', image.format)

Before resizing, python-image-resize will check whether the operation can be done. A resize is considered valid if it doesn't require to increase one of the dimension. To avoid the test add validate=False as argument:

cover = resizeimage.resize_cover(image, [200, 100], validate=False)

You can also create a two step process validation then processing using validate function attached to resized function which allows to test the viability of the resize without doing it just after validation. validate is available using the dot . operator on every resize function e.g. resize_cover.validate.

The first exemple is rewritten in the following snippet to use this feature:

from PIL import Image

from resizeimage import resizeimage

with open('test-image.jpeg', 'r+b')
    with Image.open() as image:
        is_valid = resizeimage.resize_cover.validate(image, [200, 100])

# do something else...

if is_valid:
    with Image.open('test-image.jpeg') as image:
        resizeimage.resize_cover.validate(image, [200, 100], validate=False)
        cover = resizeimage.resize_cover(image, [200, 100])
        cover.save('test-image-cover.jpeg', image.format)

Mind the fact that it's useless to validate the image twice, so we pass validate=False to resize_cover.validate.

API Reference

resize_crop(image, size, validate=True)

Crop the image with a centered rectangle of the specified size.

Crop an image with a 200x200 cented square:

from PIL import Image
from resizeimage import resizeimage

fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_crop(img, [200, 200])
img.save('test-image-crop.jpeg', img.format)
fd_img.close()

resize_cover(image, size, validate=True, resample=Image.LANCZOS)

Resize the image to fill the specified area, crop as needed. It's the same behavior as css background-size: cover property.

Resize and crop (from center) the image so that it covers a 200x100 rectangle.

from PIL import Image
from resizeimage import resizeimage

fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_cover(img, [200, 100])
img.save('test-image-cover.jpeg', img.format)
fd_img.close()

resize_contain(image, size, validate=True, resample=Image.LANCZOS, bg_color=(255, 255, 255, 0))

Resize the image so that it can fit in the specified area, keeping the ratio and without crop. It's the same behavior as css background-size: contain property. A white a background border is created.

Resize the image to minimum so that it is contained in a 200x100 rectangle is the ratio between source and destination image.

from PIL import Image
from resizeimage import resizeimage

fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_contain(img, [200, 100])
img.save('test-image-contain.jpeg', img.format)
fd_img.close()

resize_width(image, width, validate=True, resample=Image.LANCZOS)

Resize the image to the specified height adjusting width to keep the ratio the same.

Resize the image to be 200px width:

from PIL import Image
from resizeimage import resizeimage

fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_width(img, 200)
img.save('test-image-width.jpeg', img.format)
fd_img.close()

resize_height(image, height, validate=True, resample=Image.LANCZOS)

Resize the image to the specified width adjusting height to keep the ratio the same.

Resize the image to be 200px height:

from PIL import Image
from resizeimage import resizeimage

fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_height(img, 200)
img.save('test-image-height.jpeg', img.format)
fd_img.close()

resize_thumbnail(image, size, validate=True, resample=Image.LANCZOS)

Resize image while keeping the ratio trying its best to match the specified size.

Resize the image to be contained in a 200px square:

from PIL import Image
from resizeimage import resizeimage

fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_thumbnail(img, [200, 200])
img.save('test-image-thumbnail.jpeg', img.format)
fd_img.close()

resize(method, *args, **kwargs)

Resize Image with the specified method : 'crop', 'cover', 'contain', 'width', 'height' or 'thumbnail'.

from PIL import Image
from resizeimage import resizeimage

fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize('thumbnail', img, [200, 200])
img.save('test-image-thumbnail.jpeg', img.format)
fd_img.close()

Tests

pip install -r requirements.dev.txt
pip install -e .
python setup.py test

Contribute

python-resize-image is hosted at github.com/VingtCinq/python-resize-image/.

Before coding install pre-commit as git hook using the following command:

cp pre-commit .git/hooks/

And install the hook and pylint:

pip install git-pylint-commit-hook pylint

If you want to force a commit (you need a good reason to do that) use commit with the -n option e.g. git commit -n.

Support

If you are having issues, please let us know.

License

The project is licensed under the MIT License.

python-resize-image's People

Contributors

amitrao11 avatar brokenswing avatar charlesthk avatar jaric avatar mhsangar avatar siddhantgoel avatar silverkorn avatar tanguy-s avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-resize-image's Issues

AttributeError: 'function' object has no attribute 'validate'

I'm trying to resize a set of images. I followed the code mentioned here, but I keep getting this error.

The code snippet which results in the above-mentioned error is as follows -

from PIL import Image
from resizeimage import resizeimage

def resize_images(root_image_path, resized_image_path):
    for image_folder in os.listdir(root_image_path):
        
        # create corresponding folders in the resized_images folder
        if not os.path.exists(os.path.join(resize_image_path, image_folder)):
            os.makedirs(os.path.join(resize_image_path, image_folder))
                        
        # resize all images to 256 x 256
        for image in os.listdir(os.path.join(root_image_path, image_folder)):
            img = Image.open(os.path.join(root_image_path, image_folder, image), 'r')
            
            # check if image can be resized i.e. if it is too small or not
            is_valid = resizeimage.resize_cover.validate(img, [256, 256])
            
            if is_valid:
                # if image is valid, resize it to 256 x 256
                img = resizeimage.resize_cover(img, [256, 256], validate=False)
                img = img.convert("RGB")
                img.save(os.path.join(resized_image_path, image_folder, image), img.format)
            else:
                # if the image is too small, scale it up
                img = resizeimage.resize_contain(img, [256, 256], validate=False)
                img = img.convert("RGB")
                img.save(os.path.join(resized_image_path, image_folder, image), img.format)
                
                        
        print('{} done!'.format(image_folder))
    print('Resizing images complete!')

The error message that I get is shown below -

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-67bef302aaa0> in <module>
----> 1 resize_images(os.path.join(os.getcwd(), 'data/images/'), resize_image_path)

<ipython-input-18-2856c9fdcdb0> in resize_images(root_image_path, resized_image_path)
     16 
     17             # check if image can be resized i.e. if it is too small or not
---> 18             is_valid = resizeimage.resize_cover.validate(img, [256, 256])
     19 
     20             if is_valid:

AttributeError: 'function' object has no attribute 'validate'

Am I doing something wrong?
Thank you so much.

Stretching images

Hi,

Just to be sure, is this library/helper aiming on shrinking and not really stretching images?

I'm trying to upscale with the "resize_width" function to fit a given width and I get something like
'Image is too small, Image size : 1038, Required size : 1920' as error.

Thank you!

Error using resize.resize_thumbnail

Code:

orig_img = open('/home/balloch/Data/ADE20K_2016_07_26/train/ADE_train_00000001.jpg', 'r')
newimg = Image.open(orig_img)
newimg  = resizeimage.resize_thumbnail(newimg, [328,328])

Returns Error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-f53382d82a9c> in <module>()
----> 1 newimg  = resizeimage.resize_thumbnail(newimg, [328,328])

/usr/local/lib/python2.7/dist-packages/resizeimage/resizeimage.pyc in resize_thumbnail(image, size)
    164     img_format = image.format
    165     img = image.copy()
--> 166     img.thumbnail((size[0], size[1]), Image.LANCZOS)
    167     img.format = img_format
    168     return img

AttributeError: 'module' object has no attribute 'LANCZOS'

Thoughts?

Please add helper method to resize from file_name to file_name

Since your library operates on image objects from Pillow, I created this helper method:

def resize_file(in_file, out_file, size):
    with open(in_file) as fd:
        image = resizeimage.resize_thumbnail(Image.open(fd), size)
    image.save(out_file)
    image.close()

I think something like this would be very useful.

antialiasing problem

I think you can replace this code for antialiasing problem:

file: resizeimage.py

def resize(method, image, size):
"""
Helper function to access one of the resize function.
method: one among 'crop', 'cover', 'contain', 'width', 'height' or 'thumbnail'
image: a Pillow image instance
size: a list or tuple of two integers [width, height]
"""
if method not in ['crop',
'cover',
'contain',
'width',
'height',
'thumbnail']:
raise ValueError(u"method argument should be one of
'crop', 'cover', 'contain', 'width', 'height' or 'thumbnail'")
return getattr(sys.modules[name], 'resize_%s' % method)(image, size, Image.ANTIALIAS)


thanks for this library ๐Ÿ‘

Why open image with 'rw' in docs

In the docs (https://github.com/charlesthk/python-resize-image) you use 'rw' to open the images.

from PIL import Image

test_img = open('test-image.jpeg', 'rw')
img = Image.open(test_img)
img = resizeimage.resize_thumbnail(img, [200, 200])
img.save('test-image-thumbnail.jpeg', img.format)
test_img.close()

I see no sense in opening the file for writing.

BTW, it is very common to use fd_.... as variable name for file descriptors returned by open().

You use test_img. That's valid python code, but fd_img would be more easy to read.

Syntax Error

This affected our application when we found out that there is an error with the latest release.

Syntax error in resizeimage/resizeimage.py

def resize_width(image, size, resample=Image.LANCZOS)):

resize_crop rotate issue

i try test "resize_crop",
the image is rotated 90 degrees to the left,
resizeimage->def resize_crop add line crop.rotate (90) but 180 degrees to the right.
how can i fix it?

Image is too small, Image size : 300, Required size : 300

Hello,

I have a program that resizes a lot of images to smaller ones with width = 300px. However, if the original width is 300px, I get an error:

File "./06_all_together_improved.py", line 41, in process
    img = resizeimage.resize_width(img, medium_width)
  File "/home/jabba/.virtualenvs/resize_image/lib/python3.5/site-packages/resizeimage/resizeimage.py", line 31, in wrapper
    validator(image, size)
  File "/home/jabba/.virtualenvs/resize_image/lib/python3.5/site-packages/resizeimage/resizeimage.py", line 47, in _width_is_big_enough
    raise ImageSizeError(image.size[0], width)
resizeimage.imageexceptions.ImageSizeError: 'Image is too small, Image size : 300, Required size : 300'

The error message is misleading: "Image is too small, Image size : 300, Required size : 300". I think the correct behaviour in this case would be to leave the original image unchanged, as it was.

Here is a sample image for testing: https://d2r55xnwy6nx47.cloudfront.net/uploads/2015/11/KS_Ft.jpg

Best,

Laszlo

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.