由于在eclipse中,无法对BMP图片文件进行读取,因而我们要将BMP文件拆分读取
首先,关联一个BMP文件,建立个输入流来准备存储数据,.用一个一维字节数组去接收BMP文件头部信息
然后读取BMP图片的宽高
File file = new File("G:\\CP\\新文件夹\\160117\\test.bmp");
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[54];
fis.read(bytes);
int width = byteChangeToInt(bytes[21], bytes[20], bytes[19], bytes[18]);
int height = byteChangeToInt(bytes[25], bytes[24], bytes[23], bytes[22]);
System.out.println(width+" "+height);
this.setSize(width,height);
然后我们需要写一个方法将BMP文件中的byte数据转换为int类型
由于一个int类型是有四个byte组成的,所以要建立4个字节
private int byteChangeToInt(byte byte1,byte byte2,byte byte3,byte byte4) {
int value1 = ((int)byte1&0xff)<<24;
int value2 = ((int)byte2&0xff)<<16;
int value3 = ((int)byte3&0xff)<<8;
int value4 = (int)byte4&0xff;
return value1|value2|value3|value4;
之后,解析颜色,每一个像素点都有三个字节组成(三原色:红、蓝、绿),建立三个二维数组分别保存
然后调用之前的函数将byte转化为int类型
red = new int [height][width];
green = new int [height][width];
blue = new int [height][width];
然后遍历宽高上面的每一个像素点,并读取数据存入二位数粗中
for(int i=red.length-1;i>=0;i--){
for(int j=0;j<red[i].length;j++){
int b = fis.read();
int g = fis.read();
int r = fis.read();
blue[i][j] = b;
green[i][j] = g;
red[i][j] = r;
}
判断最后是否补零,如果有跳过零
int zero = 0;
if(width*3%4!=0){
zero = 4 - width*3%4;
}
重绘到界面,并关闭流
public void paint(Graphics g) {
super.paint(g);
if(red!=null){
for(int i=0;i<red.length;i++){
for(int j=0;j<red[i].length;j++){
Color color = new Color(red[i][j],green[i][j],blue[i][j]);
g.setColor(color);
g.drawLine(j, i, j, i);
}
}
}