PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 27, 2022

[FIXED] How to crop an image from the center with certain dimensions?

 July 27, 2022     crop, python, python-imaging-library     No comments   

Issue

Say we have an image with the following dimensions:

width = 200
height = 100

Say that the dimensions of our crop would be 50x50.

How can I crop an image using this new dimension from the center of the image, using Python?


Solution

Assume a crop box with the dimensions: cw, ch = 50, 50.

The center of the image is the point (w//2, h//2), where w is its width and h is its height. The square crop box which is 50 pixels on a side would also be centered there.

This means the upper left corner of the crop box would be at (w//2 - cw//2, h//2 - ch//2), and its lower right corner is at (w//2 + cw//2, h//2 + ch//2).

There's at least two ways to crop the image I can think of. The first is to use the Image.crop() method and pass it the coordinates of the rectangular crop region.

box = w//2 - cw//2, h//2 - ch//2, w//2 + cw//2, h//2 + ch//2
cropped_img = img.crop(box)

Which can be simplified mathematically to cut down on the number of divisions:

box = (w-cw)//2, (h-ch)//2, (w+cw)//2, (h+ch)//2  # left, upper, right, lower
cropped_img = img.crop(box)

Another way to do it is via the ImageOps.crop() function which is passed the size of the border on each of the four sides:

from PIL import ImageOps

wdif, hdif = (w-cw)//2, (h-ch)//2
border = wdif, hdif, wdif, hdif  # left, top, right, bottom
cropped_img = ImageOps.crop(img, border)


Answered By - martineau
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing