5 Things You Can Do With DocumentAlchemy

the DocumentAlchemy blog

 
Last Updated:
5 Things You Can Do With DocumentAlchemy

3. Resize images to a fixed width.

Suppose you have a collection of images you'd like to display in a gallery. You want an "index" page with a thumbnail for each image.

But the images are of different sizes and aspect ratios. How do you keep the index page looking orderly?

Scaling the images to a given width and heigh is clearly out, as that would distort the images.

You could crop the images to a fixed size, but without manual oversight you could easily end up with bad thumbnails.

Instead, let's scale all of our images to a fixed width while preserving the original aspect ratio. That way we can create a reasonably orderly grid without distorting the images. Images with different aspect ratios will have different heights, but they'll all share the same width and hence line up into regular columsn.

To resize an image to a fixed width while preserving the original aspect ratio we can use the /document/{ID}/rendition/{FORMAT}/transform/{ACTIONS} endpoint. This “image transform” method accepts a chain of “transformations” that do things like resize, rotate or re-color the image. In our case we'll use the S<width>,<height>, which resizes an image to the given width and height.

To specify the width of the transformed image, while allowing the height to scale “naturally” to maintain the original aspect ratio, we specify a height of 0.

Hence to scale our image to a fixed width of 240 pixels, our transformation URL will look something like this:

https://documentalchemy.com/api/v1/document/-/rendition/png/transform/S240,0

If we plug that URL into curl, we end up with something like this:

That command will transform one image at a time, but what if we have an entire directory of image to resize?

Here's a shell-script that will transform all the images enumerated on the command line:

Save the script as resize-image.sh, make sure it is executable (chmod a+x resize-image.sh) and run it like this:

./resize-image.sh 180 foo.png

to generate a rendition of foo.png that is at most 180 characters wide, or:

./resize-image.sh 240 *.png dir-one/*.png dir-two/*.png

to generate a 240-pixel-wide rendition of each PNG image found in the specified directories.

EDIT: See “Resize images to a fixed width.” in “Five Things You Can Do With the DocumentAlchemy API - Command-Line Interface Edition” for an even easier interface to this functionality.

About DocumentAlchemy

DocumentAlchemy is a RESTful web service that developers can use to add document generation, conversion and processing features to their app.

Visit our live demonstrations or interactive API reference to explore Document Alchemy's rapidly growing API for working with MS Office documents, PDFs, images, web pages and more.


Copyright © 2017 DocumentAlchemy.