No results found

Hip to be square: Cropping images with App Cloud's image transcoding API

Sometimes it's not enough to simply scale down images for your mobile app—you need to crop them as well. Say you're showing a list of news articles with square thumbnail images, as I've done here:

These images weren't born square—I made them square with a little bit of math and the help of App Cloud's image transcoder. As long as I know the original dimensions of each image, I can crop them in a consistent fashion. Here's how I crop an image to a perfect square from the center point:

 * Create a square thumbnail image, given the image url, original
 * dimensions and target size.
function getThumbnailURL(url, originalWidth, originalHeight, targetWidth) {
    // the smaller of width and height
    var minAspect = Math.min(originalWidth, originalHeight);

    // crop x
    var x = Math.floor((originalWidth / 2) - (minAspect / 2));

    // crop y
    var y = Math.floor((originalHeight / 2) - (minAspect / 2));

    // crop width
    var w = Math.round(originalWidth * (minAspect / originalWidth));

    // crop height
    var h = w;

    // the new image url
    var transcodeURL = "" +
        "?image=" + url +
        "&crop=" + [x, y, w, h].join() +
        "&width=" + targetWidth +
        "&height=" + targetWidth;

    return transcodeURL;

If you don't know the original image dimensions, you run the risk of cropping outside the image bounds, which returns an error. So how do I know the image dimensions? They're part of each <item> in my RSS feed:

    <title>HTM Ale: Our structure, your style</title>
        type="image/jpeg" />

If your RSS feed doesn't contain this data, consider using Media RSS (MRSS) or rolling your own data feed.

See a complete cropping example inside the "news-reader" template in the App Cloud Demos repository.

p.s. Get more tips and tricks (and share your own) by joining the Brightcove App Cloud discussion group on Google.