Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

How to scale an Image to the screen size in Java ME

From Wiki
Jump to: navigation, search
Article Metadata
Created: microedition (28 Aug 2008)
Last edited: hamishwillee (08 Aug 2013)

This article shows an approach for scaling an image to fit the screen using Java ME. This is an alternative to providing images that suit different possible screen sizes.



Method Specification

Method Name CreateScaledImage
imgOldImage Image that we have to fit
iNewWidth The new witdth of the image
iNewHeight The new height of the image
Return Value
New image with the new size

Source file

public static Image CreateScaledImage( Image imgOldImage, int iNewWidth, int iNewHeight  )
Image imgNewImage = null;
final int iOldWidth = imgOldImage.getWidth();
final int iOldHeight = imgOldImage.getHeight();
int iOldRGBArray[] = new int[iOldWidth * iOldHeight];
iOldRGBArray = imgOldImage.getRGB( iOldRGBArray, 0, iOldWidth, 0, 0, iOldWidth, iOldHeight);
int iNewRGBArray[] = new int[iNewWidth * iNewHeight];
for (int yy = 0; yy < iNewHeight; yy++)
int dy = yy * iOldHeight / iNewHeight;
for (int xx = 0; xx < iNewWidth; xx++)
int dx = xx * iOldWidth / iNewWidth;
iNewRGBArray[(iNewWidth * yy) + xx] = iOldRGBArray[(iOldWidth * dy) + dx];
imgNewImage = Image.createRGBImage(iNewRGBArray, iNewWidth, iNewHeight, true);
return imgNewImage;


We could use this method in a Canvas Object in this way:

public class MyCanvas extends GameCanvas
private Image objBKGImage = null;
public void paint(Graphics g)
iViewH = this.getHeight();
iViewW = this.getWidth();
// load the background image
if (objBKGImage== null)
objBKGImage = Image.createImage("/res/Logo_150_53.png");
objBKGImage = CreateScaledImage(objBKGImage, iViewW, iViewH)
catch (IOException ex)
// draw background
if (objBKGImage!= null)
(int)iViewW / 2,
(int)iViewH / 2,
Graphics.VCENTER | Graphics.HCENTER );


Image resizing is processing intensive, and the performance of the code provided depends on the resolution of the original image. Furthermore, if the aspect ratio (width/height) of the screen in question does not match the original image, the result can look rather stretched or squashed. The use of images as backgrounds should also be avoided on devices where the phone can switch from portrait to landscape mode.

This page was last modified on 8 August 2013, at 06:42.
61 page views in the last 30 days.