Scales image simply by picking convenient pixels to the scaled image - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Scale

Description

Scales image simply by picking convenient pixels to the scaled image

Demo Code


import java.io.InputStream;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

public class Main{
    /**//from   ww  w  . ja  v  a  2 s .  c om
     * Scales image simply by picking convenient pixels to the scaled image
     * @return Returns scaled image
     */
    public static Image quickNDirty(Image original, int newWidth,
            int newHeight) {
        int[] rawInput = new int[original.getHeight() * original.getWidth()];
        original.getRGB(rawInput, 0, original.getWidth(), 0, 0,
                original.getWidth(), original.getHeight());

        int[] rawOutput = new int[newWidth * newHeight];

        int YD = (original.getHeight() / newHeight) * original.getWidth()
                - original.getWidth();
        int YR = original.getHeight() % newHeight;
        int XD = original.getWidth() / newWidth;
        int XR = original.getWidth() % newWidth;
        int outOffset = 0;
        int inOffset = 0;

        for (int y = newHeight, YE = 0; y > 0; y--) {
            for (int x = newWidth, XE = 0; x > 0; x--) {
                rawOutput[outOffset++] = rawInput[inOffset];
                inOffset += XD;
                XE += XR;
                if (XE >= newWidth) {
                    XE -= newWidth;
                    inOffset++;
                }
            }
            inOffset += YD;
            YE += YR;
            if (YE >= newHeight) {
                YE -= newHeight;
                inOffset += original.getWidth();
            }
        }
        return Image.createRGBImage(rawOutput, newWidth, newHeight, true);
    }
}

Related Tutorials