Skip to content

Instantly share code, notes, and snippets.

@kaplas
Created November 1, 2012 11:31
Show Gist options
  • Save kaplas/3993136 to your computer and use it in GitHub Desktop.
Save kaplas/3993136 to your computer and use it in GitHub Desktop.
private Image scaleImage(Image sourceImage, int newImageWidth, int newImageHeight){
// width of original source image
int srcWidth = sourceImage.getWidth();
// height of original source image
int srcHeight = sourceImage.getHeight();
// An array for RGB, with the size of original image)
int rgbSource[] = new int[srcWidth*srcHeight];
// An array for RGB, with the size of scaled image)
int rgb2Scaled[] = new int[newImageWidth*newImageHeight];
// Get the RGB array of source image
sourceImage.getRGB(rgbSource,0,srcWidth,0,0,srcWidth,srcHeight);
// calculations and bit shift operations to optimize the for loop
int tempScaleRatioWidth = ((srcWidth<<16) / newImageWidth);
int tempScaleRatioHeight = ((srcHeight<<16) / newImageHeight);
int i = 0;
for (int y = 0; y < newImageHeight; y++) {
for (int x = 0; x < newImageWidth; x++) {
rgb2Scaled[i++]=rgbSource[(srcWidth*((y * tempScaleRatioHeight)>>16))+((x * tempScaleRatioWidth)>>16)];
}
}
//Create an RGB image from rgbScaled array
return Image.createRGBImage(rgb2Scaled,newImageWidth,newImageHeight,true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment