Resizing an image in swing

前端 未结 4 1206
名媛妹妹
名媛妹妹 2021-01-06 02:46

I have snippet of code that I am using for the purpose of resizing an image to a curtain size (I want to change the resolution to something like 200 dpi). Basically the reas

4条回答
  •  北海茫月
    2021-01-06 03:13

    Try this CODE to resize image :

    public static Image scaleImage(Image original, int newWidth, int newHeight) {
        //do nothing if new and old resolutions are same
        if (original.getWidth() == newWidth && original.getHeight() == newHeight) {
            return original;
        }
    
        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];
        // YD compensates for the x loop by subtracting the width back out
        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, false);
    }
    

提交回复
热议问题