Question

i have created an image from the image url(lcdui image)

HttpConnection c = (HttpConnection) Connector.open(imageurl);
int len = (int)c.getLength();

if (len > 0) 
{
is = c.openDataInputStream();
byte[] data = new byte[len];
is.readFully(data);

img = Image.createImage(data, 0, len);

i want to set height and width to this?and i want to display

Was it helpful?

Solution

You can't set width and height to Image. But, you can resize the image using the below method.

public Image resizeImage(Image src, int screenHeight, int screenWidth) {
        int srcWidth = src.getWidth();

        int srcHeight = src.getHeight();
        Image tmp = Image.createImage(screenWidth, srcHeight);
        Graphics g = tmp.getGraphics();
        int ratio = (srcWidth << 16) / screenWidth;
        int pos = ratio / 2;

        //Horizontal Resize        

        for (int index = 0; index < screenWidth; index++) {
            g.setClip(index, 0, 1, srcHeight);
            g.drawImage(src, index - (pos >> 16), 0);
            pos += ratio;
        }

        Image resizedImage = Image.createImage(screenWidth, screenHeight);
        g = resizedImage.getGraphics();
        ratio = (srcHeight << 16) / screenHeight;
        pos = ratio / 2;

        //Vertical resize

        for (int index = 0; index < screenHeight; index++) {
            g.setClip(0, index, screenWidth, 1);
            g.drawImage(tmp, 0, index - (pos >> 16));
            pos += ratio;
        }
        return resizedImage;

    }

OTHER TIPS

You don't need to set the width and height because during image loading this information is loaded and set. So, if the image is 320x100, your code will create a 320x100 image. img.getWidth() would return 320. img.getHeight() would return 100.

It is not possible to change the width and height of an Image object. You can just query its width and height.

Your image is ready to be presented in a ImageItem object ou blit in a canvas.

The accepted answer didn't work for me (as it left a white band along the bottom of the image when reducing the image size - despite keeping the same aspect ratio). I found a snippet code that works from the CodeRanch forum.

Here is that snippet, cleaned up:

protected static Image resizeImage(Image image, int resizedWidth, int resizedHeight) {

    int width = image.getWidth();
    int height = image.getHeight();

    int[] in = new int[width];
    int[] out = new int[resizedWidth * resizedHeight];

    int dy, dx;
    for (int y = 0; y < resizedHeight; y++) {

        dy = y * height / resizedHeight;
        image.getRGB(in, 0, width, 0, dy, width, 1);

        for (int x = 0; x < resizedWidth; x++) {
            dx = x * width / resizedWidth;
            out[(resizedWidth * y) + x] = in[dx];
        }

    }

    return Image.createRGBImage(out, resizedWidth, resizedHeight, true);

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top