Implementing the MIDlet Utils class

To implement the Utils class:

  1. Create the Utils.java class file.

  2. Import the required packages and classes.

    package com.nokia.example.imagescaler;
    
    import javax.microedition.lcdui.Image;
  3. Create the Utils class.

    public class Utils {
  4. Create required variables.

    public static final String PHOTOS_DIR = System.getProperty("fileconn.dir.photos");
  5. Create the scaleImage method. This method scales the given image to the given new size.

    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);
    }
    }