2011-02-08 24 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);