Utils.java

/**
 * Copyright (c) 2013 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */

package com.nokia.example.imagescaler;

import javax.microedition.lcdui.Image;

public class Utils {
    // Constants
    public static final String PHOTOS_DIR = System.getProperty("fileconn.dir.photos");

    /**
     * Scales the given image to the given new size.
     * @param image The image to scale.
     * @param newWidth The new, target width.
     * @param newHeight The new, target height.
     * @return A newly created scaled image instance or null in case of an error.
     * @throws OutOfMemoryError
     */
    public static Image scaleImage(Image image,
                                   final int newWidth,
                                   final int newHeight)
        throws OutOfMemoryError
    {
        if (image == null || newWidth <= 0 || newHeight <= 0) {
            return null;
        }
        
        final int sourceWidth = image.getWidth();
        final int sourceHeight = image.getHeight();
        int[] rgbImageData = null;
        
        if (rgbImageData == null) {
            rgbImageData = new int[sourceWidth * sourceHeight];
            image.getRGB(rgbImageData, 0, sourceWidth, 0, 0, sourceWidth, sourceHeight);
        }
        
        int rgbImageScaledData[] = new int[newWidth * newHeight];
        
        int tempScaleRatioWidth = ((sourceWidth << 16) / newWidth);
        int tempScaleRatioHeight = ((sourceHeight << 16) / newHeight);
        int i = 0;
        
        for (int y = 0; y < newHeight; y++) {
            for (int x = 0; x < newWidth; x++) {
                rgbImageScaledData[i++] =
                    rgbImageData[(sourceWidth * ((y * tempScaleRatioHeight) >> 16))
                                 + ((x * tempScaleRatioWidth) >> 16)];
            }
        }
        
        return Image.createRGBImage(rgbImageScaledData, newWidth, newHeight, true);
    }
}