──────────────────────────────────────

55. Work with Spreadsheets, PDFs and Images · Resize an Image Copy

Predict dimensions for an image that fits inside a box, then measure the saved copy.

Lesson files · lessons/documents-and-images/resize-image-copies

Before you start
- Read two dimensions and a limit from supplied data.
- Use division and multiplication to convert numbers.
- Keep the original input files when creating an output.

By the end
- Use one scale for the width and height to keep the image in proportion.
- Use a maximum size without enlarging an image that already fits.
- Explain how to check the pixel size of a saved copy.

Where you can use it
Send a set of posters for a small web gallery. Make each one fit in a thumbnail box and keep the full-size originals for printing.

An image has a width and height measured in pixels. To fit a poster in a square box, compare the limit with both dimensions. Choose the smaller scale so both sides fit. Include 1 as a possible scale so a small image stays the same size.

In Studio, use the numbers to estimate the size and round to whole pixels. In the local lab, Pillow opens the real image and thumbnail() scales it to fit, keeping its proportions. Save to a different path and reopen the copy to check its actual pixel size. The library may round a dimension differently from your estimate.

Predict
Why does a 600 by 300 image fit as 300 by 150?
- Both sides use the same scale of one half.
- The height stays at 300.

Worked example (example.py)

width, height = 600, 300
limit = 300
scale = min(1, limit / width, limit / height)
print(f"{round(width * scale)} x {round(height * scale)}")


Example result
300 x 150

Read three positive whole numbers as a JSON list. They give the width, height and square size limit. Estimate the result using the same scale for both sides. Round each side and keep it at least one pixel. Print Size: width x height using the new values.

Starter program (starter.py)

import json

width, height, limit = json.loads(input())
print(f"Size: {width} x {height}")


Starter input
[480,960,320]

Hint
Use min() to choose among 1, limit divided by width and limit divided by height. Keep each rounded dimension at least 1 with max().

Case 1. Try the sample
Input
[480,960,320]
Expected output
Size: 160 x 320

Case 2. Already fits
Input
[160,160,320]
Expected output
Size: 160 x 160

Case 3. Very thin image
Input
[2,1000,100]
Expected output
Size: 1 x 100

Stretch
Try a wide image and a tall image with the same longest side. Predict which dimension reaches the limit in each case.

Reflect
Why do you use the same scale for both sides?

Check your prediction
Both sides use the same scale of one half. Applying the same scale to both dimensions keeps the image in proportion.
