编辑:我已更改了一些代码以反映AlamasB所说的内容。我仍然不明白应该如何填充字节数组以及需要做什么转换。将图像的像素复制到java中的画布中
我试图操纵用户上传的图像的像素,并将新图像写入画布。现在我只是试图复制原始图像而不改变像素的RGB。我一直在同一个地方停留了很长一段时间,无法确定下一步该去哪里。在代码的第一部分,我制作了用户上传的原始图像的副本。
Image image = imageView.getImage();
PixelReader pixelReader = image.getPixelReader();
PixelFormat format = pixelReader.getPixelFormat();
int width= (int)image.getWidth();
int height = (int) image.getHeight();
GraphicsContext gc = canvas.getGraphicsContext2D();
PixelWriter pw = gc.getPixelWriter();
byte[] imageData = new byte[width * height * 4];
imageData = createImageData(imageData, pixelReader, width, height);
//..
//...the next function populates my byte array with what's in the image
public byte[] createImageData(byte[] imageData, PixelReader pr, int width, int height){
int i = 0;
for(int y=0; y<height; y++){
for(int x = 0; x < width; x++){
int argb = pixelReader.getArgb(x, y);
imageData[i] = (byte) argb;
imageData[i+1] = (byte) argb;
imageData[i+2] = (byte) argb;
i+=3;
pw.setArgb(x, y, argb);
}
}
return imageData;
}
编辑:不再使用此功能。下一个功能让我很困惑。我指的是http://docs.oracle.com/javafx/2/image_ops/jfxpub-image_ops.htm作为参考,但我无法弄清楚发生了什么。
//...
//... the next function sets the pixels of the canvas to what's in the byte array
public void drawImageData(byte[] imageData, PixelWriter pw, int width, int height){
boolean on = true;
PixelFormat<ByteBuffer> pixelFormat = PixelFormat.getByteRgbInstance();
for(int y = 50; y < 150; y+=height){
for(int x = 50; x < 150; x+=width){
if(on){
pw.setPixels(x, y, width, height, pixelFormat, imageData, 0, width*3);
}
on = !on;
}
on=!on;
}
}
所以是oracle的方法例如不工作的问题,或者您希望它是如何工作的解释? – fakataha
[this](http://docs.oracle.com/javafx/2/api/javafx/scene/image/PixelWriter.html#setPixels(int,%20int,%20int,%20int,%20javafx.scene.image .PixelFormat,%20int [],%20int,%20int))是开始阅读的好时机。您提供的方法不会创建图像的副本。 – Paul
我很高兴你链接到setPixels()方法,因为这就是让我困惑的东西。它表示前两个参数是写入数据的x和y坐标。它是指画布的x和y,还是我需要知道相对于我的根对象的x和y位置? –