给定BufferedImage 图像,这里有 3 种方法来创建“深”复制子图像:
// Create an image
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_4BYTE_ABGR);
// Fill with static
new Random().nextBytes(((DataBufferByte) image.getRaster().getDataBuffer()).getData());
围绕您从getData(rect) 获得的Raster 的深层副本创建一个图像。这涉及转换为WritableRaster,因此它可能会与某些Java 实现或将来中断。应该很快,因为您只复制一次数据:
// Get sub-raster, cast to writable and translate it to 0,0
WritableRaster data = ((WritableRaster) image.getData(new Rectangle(25, 25, 50, 50))).createWritableTranslatedChild(0, 0);
// Create new image with data
BufferedImage subOne = new BufferedImage(image.getColorModel(), data, image.isAlphaPremultiplied(), null);
另一种选择,以“正常方式”创建子图像,然后将光栅复制到新图像中。涉及创建一个子光栅,仍然只复制一次(并且没有强制转换):
// Get subimage "normal way"
BufferedImage subimage = image.getSubimage(25, 25, 50, 50);
// Create empty compatible image
BufferedImage subTwo = new BufferedImage(image.getColorModel(), image.getRaster().createCompatibleWritableRaster(50, 50), image.isAlphaPremultiplied(), null);
// Copy data into the new, empty image
subimage.copyData(subTwo.getRaster());
最后,更简单的方法是在新的空图像上绘制子图像。可能会稍微慢一些,因为它涉及渲染管道,但我认为它应该仍然可以合理地执行。
// Get subimage "normal way"
BufferedImage subimage = image.getSubimage(25, 25, 50, 50);
// Create new empty image of same type
BufferedImage subThree = new BufferedImage(50, 50, image.getType());
// Draw the subimage onto the new, empty copy
Graphics2D g = subThree.createGraphics();
try {
g.drawImage(subimage, 0, 0, null);
}
finally {
g.dispose();
}