java - 平移 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)
}
}
解决方案
这是您可以执行的 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));
}
}
您也可以稍微调整一下以就地修改图像。
推荐阅读
- typescript - 转换为箭头函数
- java - 将 Spring JPA 一对多对象编组为 JSON
- xml - XML解析Oracle
- php - 我怎样才能重新格式化这个数组?
- r - 不断出现错误,表明示例在 R Studio 云中不起作用,我不知道为什么
- html - 使用谷歌脚本时如何在“发送消息”按钮后重定向到感谢页面?
- python - python安装boto3-即使pypi显示索引也找不到版本
- oracle - 无法创建 Oracle XE HR 示例
- git - git 如何应用从 git diff --no-index /backup /source 生成的补丁
- r - Multi condition filter in R