Image Crop, Rotation and Scaling in Qt for Python: Qt Image Viewer Part 2

in #programming8 years ago

Screenshot from 2018-06-01 14-20-31.png

In the spec for my Image Viewer application, one of the nice to have goals was the ability to do transformations on the pictures.

When you take a picture with your phone, as I often do, the photographs can turn out to be the wrong orientation, size, or have superfluous information, so ideally we need:

  • Crop
  • Rotate 90 degrees
  • Resize

Here is how to do that with the Qt library we selected.

You recall that we were loading the image using QPixmap? Well, we can add the portion of that image we need, essentially cropping it (200 pixels wide, 200 deep, starting at the top, left corner):

# load and crop pic
picture = QPixmap("background.png").copy(0, 0, 200, 200)

To rotate 90 degrees we create a QTransform and apply it thus:

# rotate
transform = QTransform().rotate(90)
picture = picture.transformed(transform)

Scaling is done with a similar method, using scale instead. Here we double the size:

# scale
transform = QTransform().scale(2, 2)
picture = picture.transformed(transform)

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.099
BTC 62848.28
ETH 1779.86
USDT 1.00
SBD 0.38