如何在 java 中进行像素完美放大?

how do I do pixel perfect upscaling in java?

我有很多像素艺术图片需要放大到两倍大小。

需要做到这一点,使图像中的每个像素都变成一组 2x2 像素,颜色完全相同,没有颜色混合。

示例:

f 我使用 ImageIO 将 .png 图像作为 BufferedImage 读入

BufferedImage foo = ImageIO.read(new File("C:\path\to\image.png"));

我该如何放大它,使其不会混合像素?

希望对你有帮助

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageCovertTest {

public static void main(String[] args) throws IOException {
    BufferedImage foo = ImageIO.read(new File("path/to/image"));
    BufferedImage rs = cover(foo, 2);// cover X2
    ImageIO.write(rs, "png", new File("path/to/output"));
}


private static int[][] convertToPixels(BufferedImage image) {

    final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
    final int width = image.getWidth();
    final int height = image.getHeight();
    final boolean hasAlphaChannel = image.getAlphaRaster() != null;

    int[][] result = new int[height][width];
    if (hasAlphaChannel) {
        final int pixelLength = 4;
        for (int pixel = 0, row = 0, col = 0; pixel + 3 < pixels.length; pixel += pixelLength) {
            int argb = 0;
            argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
            argb += ((int) pixels[pixel + 1] & 0xff); // blue
            argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
            argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
            result[row][col] = argb;
            col++;
            if (col == width) {
                col = 0;
                row++;
            }
        }
    } else {
        final int pixelLength = 3;
        for (int pixel = 0, row = 0, col = 0; pixel + 2 < pixels.length; pixel += pixelLength) {
            int argb = 0;
            argb += -16777216; // 255 alpha
            argb += ((int) pixels[pixel] & 0xff); // blue
            argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
            argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
            result[row][col] = argb;
            col++;
            if (col == width) {
                col = 0;
                row++;
            }
        }
    }
    return result;
}

public static BufferedImage cover(BufferedImage image, int range) {
    int[][] pixels = convertToPixels(image);
    int width = image.getWidth();
    int height = image.getHeight();

    BufferedImage imageResult = new BufferedImage(width* range, height* range, BufferedImage.TYPE_INT_ARGB);
    for (int x = 0; x < width * range; x ++){
        for (int y = 0; y < height * range; y++) {
            imageResult.setRGB(x, y, pixels[y/ range][x/ range]);
            }
        }
        return imageResult;
    }

}