jsbueno / terminedia

Python3 library for multimedia functions at the command terminal
GNU Lesser General Public License v3.0
100 stars 8 forks source link

[Question] How to limit size of image? #24

Closed paw-lu closed 3 years ago

paw-lu commented 3 years ago

Trying to use this library to convert images to block characters. So far it's working great.

One point of confusion for me is how to control the size of the output. For context, I'm trying to preserve the ratio of the image, but constrain either its height or width so that it can fit within an arbitrary space.

Here I attempt—and fail—to read in an image and constrain its output to 30 characters in width.

import io

import terminedia
from PIL import Image

screen = terminedia.Screen(backend="ANSI")
resolution = "square"
size = terminedia.V2(x=30, y=30)

image = Image.open("Ent_Steven-Universe_SOCIAL.jpeg")
img = terminedia.shape(
    image,
    size=size,
    promote=True,
    resolution=resolution,
)
output = io.StringIO()
img.render(output=output, backend="ANSI")

print(output.getvalue())
print("-" * 30)  # Ruler to visualize 30 units across 
Screen Shot 2021-08-20 at 8 08 15 PM

It renders perfectly, but is wider than 30 characters.

I'm trying to understand:

  1. What does the size argument actually do? The resulting image is not 30x30.
  2. What's the best way to accomplish my goal—preserving the original aspect ratio of an image while restraining the height and the width to be within a certain number of characters?

(Again) thanks for the project!

paw-lu commented 3 years ago

Follow up:

Tried different resolution values for the same x and y values in size, and get different sizes and aspect ratios.

Why is this the case?

Screen Shot 2021-08-21 at 3 42 56 PM
jsbueno commented 3 years ago

The code would try to keep the aspect ratio of the source image, no matter what "size" was passed. (but, when using any resolution other than "square" the aspect ratio of the terminal is 1:2, so all images would look-like broken). I just updated that code to respect the given size, and keep the aspect-ratio if one of the size components is set to "None".

(that is branch 'main' right now, and should be the behavior on 0.4.2 and later releases)

paw-lu commented 3 years ago

but, when using any resolution other than "square" the aspect ratio of the terminal is 1:2, so all images would look-like broken

Got it. Thanks for the explanation!

I just updated that code to respect the given size, and keep the aspect-ratio if one of the size components is set to "None".

Thanks! It's appreciated. I look forward to trying it out!

paw-lu commented 3 years ago

Just integrated the changes and wanted to say thanks for helping me out!