首页 > 解决方案 > 平移 BufferedImage

问题描述

如何删除 BufferedImage 最左侧垂直列的 50px,并将其复制到与原始 BufferedImage 大小相同的新 BufferedImage 中?

class TestCopyImage {

    var img: BufferedImage? = null
    private val rnd = Random()

    fun create(screenWidth: Int, screenHeight: Int) {
        img = BufferedImage(screenWidth, screenHeight, BufferedImage.TYPE_INT_RGB)

        //Grab the graphics object off the image
        val graphics = img!!.createGraphics()

        //val stroke: Stroke = BasicStroke(1f)
        //graphics.setStroke(stroke);

        // Fill the image buffer
        for (i in 1..screenWidth) {
            for (j in 1..screenHeight) {
                val r: Int = rnd.nextInt(255)
                val g: Int = rnd.nextInt(255)
                val b: Int = rnd.nextInt(255)
                val randomColor = Color(r, g, b)
                graphics.paint = randomColor
                graphics.fill(Rectangle(i , j , 1, 1))
            }
        }

        // Get a subimage, deleting 50 pixels of the left-most vertical portion.
        img = img!!.getSubimage(50, 0, screenWidth - 50 , screenHeight)

        // TODO Now copy that into a new image, same size as the original buffer?
        img = BufferedImage(screenWidth, screenHeight, BufferedImage.TYPE_INT_RGB)
    }
}

标签: javakotlin

解决方案


这是您可以执行的 Java 版本:

int panDist = 50;

BufferedImage subImg = img.getSubimage(panDist, 0, img.getWidth() - panDist, img.getHeight());

BufferedImage newImg = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
for (int x = 0; x < subImg.getWidth(); ++x) {
    for (int y = 0; y < subImg.getHeight(); ++y) {
        newImg.setRGB(x, y, subImg.getRGB(x, y));
    }
}

不过,子图像并不是真正必要的,您可以跳过它并直接执行此操作:

int panDist = 50;

BufferedImage newImg = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
for (int x = panDist; x < img.getWidth(); ++x) {
    for (int y = 0; y < img.getHeight(); ++y) {
        newImg.setRGB(x - panDist, y, img.getRGB(x, y));
    }
}

您也可以稍微调整一下以就地修改图像。


推荐阅读