开发者

How to initialize BufferedImage fast in Java?

I have the following Java code:

public static BufferedImage createImage(byte[] data, int width, int height)
{
  BufferedImage res = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

  byte[] rdata = ((DataBufferByte)res.getRaster().getDataBuffer()).getData();

  for (int y = 0; y < height; y++) {
    int yi = y * width;
    for (int x = 0; x < width; x++) {
      rdata[yi] = data[yi];
      yi++;
    }
  }

  return res;
}

Is there a faster way to do this?

In C++ I would use memcpy, but in Java?

Or maybe it is possible to i开发者_如何学运维nitialize the result image with the passed data directly?


Well, to copy the array quickly you can use System.arraycopy:

System.arraycopy(data, 0, rdata, 0, height * width);

I don't know about initializing the BufferedImage to start with though, I'm afraid.

Have you tried:

res.getRaster().setDataElements(0, 0, width, height, data);

?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜