gpt4 book ai didi

java - 平移 BufferedImage

转载 作者:行者123 更新时间:2023-12-02 09:06:41 30 4
gpt4 key购买 nike

如何删除 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)
}
}

最佳答案

这是您可以执行的 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));
}
}

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

关于java - 平移 BufferedImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59763092/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com