Saturday, August 29, 2009

Resize Image in Blackberry

Sometimes it is needed to resize an image.
Resizing an image to a smaller resolution may cause some distortion of the image.


Image can be programatically resize in many ways.


Approach 1
----------

private Bitmap getScaledBitmapImage(EncodedImage image, int width, int height)
{
// Handle null image
if (image == null)
{
return null;
}

//return bestFit(image.getBitmap(), width, height);

int currentWidthFixed32 = Fixed32.toFP(image.getWidth());
int currentHeightFixed32 = Fixed32.toFP(image.getHeight());

int requiredWidthFixed32 = Fixed32.toFP(width);
int requiredHeightFixed32 = Fixed32.toFP(height);

int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);

image = image.scaleImage32(scaleXFixed32, scaleYFixed32);

return image.getBitmap();
}



Approach 2
------------

public static Bitmap resizeBitmap(Bitmap image, int width, int height)
{
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();

// Need an array (for RGB, with the size of original image)
int rgb[] = new int[imageWidth * imageHeight];

// Get the RGB array of image into "rgb"
image.getARGB(rgb, 0, imageWidth, 0, 0, imageWidth, imageHeight);

// Call to our function and obtain rgb2
int rgb2[] = rescaleArray(rgb, imageWidth, imageHeight, width, height);

// Create an image with that RGB array
Bitmap temp2 = new Bitmap(width, height);

temp2.setARGB(rgb2, 0, width, 0, 0, width, height);

return temp2;
}

private static int[] rescaleArray(int[] ini, int x, int y, int x2, int y2)
{
int out[] = new int[x2*y2];
for (int yy = 0; yy < y2; yy++)
{
int dy = yy * y / y2;
for (int xx = 0; xx < x2; xx++)
{
int dx = xx * x / x2;
out[(x2 * yy) + xx] = ini[(x * dy) + dx];
}
}
return out;
}




Approach 3
----------

public static Bitmap bestFit(Bitmap image, int maxWidth, int maxHeight)
{
// getting image properties
int w = image.getWidth();
int h = image.getHeight();

// get the ratio
int ratiow = 100 * maxWidth / w;
int ratioh = 100 * maxHeight / h;

// this is to find the best ratio to
// resize the image without deformations
int ratio = Math.min(ratiow, ratioh);

// computing final desired dimensions
int desiredWidth = w * ratio / 100;
int desiredHeight = h * ratio / 100;

//resizing
return resizeBitmap(image, desiredWidth, desiredHeight);
}


1 comment: