這是一個有點難以閱讀的代碼,但如果我們走線槽源代碼:
public BufferedImage More ...getSubimage (int x, int y, int w, int h) {
return new BufferedImage (colorModel,
raster.createWritableChild(x, y, w, h,
0, 0, null),
colorModel.isAlphaPremultiplied(),
properties);
}
此方法調用raster.createWritableChild
讓我們來看看...
public WritableRaster More ...createWritableChild(int parentX, int parentY,
int w, int h,
int childMinX, int childMinY,
int bandList[]) {
if (parentX < this.minX) {
throw new RasterFormatException("parentX lies outside raster");
}
if (parentY < this.minY) {
throw new RasterFormatException("parentY lies outside raster");
}
if ((parentX+w < parentX) || (parentX+w > this.width + this.minX)) {
throw new RasterFormatException("(parentX + width) is outside raster");
}
if ((parentY+h < parentY) || (parentY+h > this.height + this.minY)) {
throw new RasterFormatException("(parentY + height) is outside raster");
}
SampleModel sm;
// Note: the SampleModel for the child Raster should have the same
// width and height as that for the parent, since it represents
// the physical layout of the pixel data. The child Raster's width
// and height represent a "virtual" view of the pixel data, so
// they may be different than those of the SampleModel.
if (bandList != null) {
sm = sampleModel.createSubsetSampleModel(bandList);
}
else {
sm = sampleModel;
}
int deltaX = childMinX - parentX;
int deltaY = childMinY - parentY;
return new WritableRaster(sm,
getDataBuffer(),
new Rectangle(childMinX,childMinY,
w, h),
new Point(sampleModelTranslateX+deltaX,
sampleModelTranslateY+deltaY),
this);
}
正如你所看到的,創建的新光柵具有與其父級相同的DataBuffer(如果更新子圖像,可能允許修改整個圖像),因此當您執行此操作時,
img .getRaster .getDataBuffer
你得到整個圖像的databuffer。
我沒有當然的測試,但BufferedImage.getData(Rectangle rect)
應該返回一個新的光柵有自己的DataBuffer,然後做像你一樣
見http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/awt/image/BufferedImage.java#BufferedImage.getData%28%29
編輯:安東哈拉爾(OP)最終測試答案
(defn get-data [img x y w h]
(-> (.getData img (Rectangle. x y w h))
.getDataBuffer
.getData))
來自'getSubImage'的文檔:'返回的BufferedImage與原始圖像共享相同的數據數組。'這不是原因嗎? https://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html#getSubimage(int,%20int,%20int,%20int) – OlegTheCat