2011-02-08 26 views
1

我有以下的Java代码:如何在Java中快速初始化BufferedImage?

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; 
} 

有一个更快的方法来做到这一点?

在C++中我会使用memcpy,但在Java?

也许有可能直接用传递的数据初始化结果图像?

+0

你需要它快多少? – leonm 2011-02-08 09:23:30

+0

没有确切的数字,我只是新的,这种方式很慢,我希望代码更快/更好。 – 2011-02-08 09:44:55

回答

6

好了,到阵列快速复制,你可以使用System.arraycopy

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

我不知道初始化BufferedImage下手不过,我怕做。

你试过:

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