Intelligently Determine Image Size in Python
<p>I would like to use Python to intelligently choose dimensions (in inches) for pictures.  Were I to do this manually, I would open the picture in some photo editing software and resize the image until it seemed 'good'.  </p>

<p>Other answers I've seen on SO have pre-specified dimensions, but in this case that's what I want the program to determine.  I'm terribly new to image processing, so I'm hesitant to be more specific.  However, I <em>think</em> I want to choose a size such that DPI >= 300.  All of these images will end up printed, which is why I'm focused on DPI as a metric.  A horrible brute force way might be:</p>

<pre><code>from PIL import Image
import numpy as np
import bisect

min_size = 1
max_size = 10
sizes = np.linspace(min_size, max_size)
for size in sizes:   
    im = Image.open(im_name)
    im.thumbnail((size, size), Image.ANTIALIAS) #assumes square images
    dpi_vals.append(im.info['dpi']))
best_size = sizes[bisect.bisect(dpi_vals, 300)]
</code></pre>

<p>This strikes me as very inefficient and I'm hoping someone with more experience has a smarter way.</p>

<p>I guess I asked a bit prematurely.  This hinges more on understanding resolution vs. DPI than it does on programming.  Once I learned more, the answer becomes quite easy.  Digital images have resolutions, while printed images have DPI.  To choose the size of a digital image such that, if printed, that image will have 300 DPI is as simple as: pixels / 300.  In the specific case of <code>PIL</code>, the following code works fine:</p>

<pre><code>import PIL

im = Image.open(im_name)
print_ready_width = im.size[0] / 300
</code></pre>

<p>Then the image will have 300 DPI if printed at <code>print_read_width</code>.</p>

python image-processing python-imaging-library