2011-04-30 38 views
0

嗨 我有一个尺寸为640 * 480像素的图像数据,数据格式为0和1,在一个txt文件中。因此文本文件中有640 * 480 = 307200个字符(0和1)。 0表示原始图像中没有任何内容(例如黑色背景),1表示存在(例如,用户正在站立并且与用户blob有关),因此它不会被误认为RGB或字节数据。将像素数据转换为java中的图像

我需要读取它并将其转换为java中大小为640 * 480像素的图像,其中用0表示的像素可以设置为一种颜色(例如黑色),另一种颜色设置为1(例如白色)。
我该怎么做?感谢帮助。

+0

阅读'txt'逐字符文件并使用if-else语句相应地绘制图像。 – Alpine 2011-04-30 19:20:53

回答

4

首先,你需要读它。如果你知道它的宽度,你可以做这样的事情:

BufferedReader in = new BufferedReader(new FileReader("myfile.txt")); 
boolean[][] mask = new boolean[640][480]; 
int i = -1; 
int count = 0; 
while((i = in.read()) !- -1) { 
    int x = count % 640; 
    int y = count/640; 
    mask[x][y] = (i == '1'); 
    count++; 
} 

然后你就可以画这样

paint(Graphics g) { 
    g.setColor(Color.BLACK); 
    g.drawRect(0,0,640,480); // draw the black background 

    // mask it with white 
    g.setColor(Color.WHITE); 
    for(int x = 0; x < 640); x++) { 
     for(int y = 0; y < 480); y++) { 
      if(mask[x][y]) g.drawRect(x,y,1,1); 
     } 
    } 
} 
+0

thankyou glowcoder,但我不知道如何使用油漆(图形克)功能.. – Nohsib 2011-04-30 20:13:26

+0

了解它...谢谢吨! – Nohsib 2011-04-30 20:31:53