ITeye博客

保存bmp自画图形

孙瑞鸿 · 2013-07-02 00:07 · Markdown

保存自画图形(bmp图像) 分析: 首先:要做一个画板出来,实现画各种图形(这个就很简单,不多说了) 其次:怎样将这个图片保存起来,保存的目的就是再一次打开,这就要求我们在保存 的时候要有一定的规则!bmp的规则我们已经很熟悉了!接下来就看一下具体操作吧!

此次我们使用的是BufferedImage得到画布,利用BufferedImage的一些方法截取 指定大小的图片、取得图片上的图片信息,并将其写入指定路径的文件中。

java.awt.Robot ro=new java.awt.Robot();	
	/*
	* myCanvas.getLocation().x,myCanvas.getLocation().y
	* 得到当前容器的x,y坐标值
	*/
	Rectangle rt=new Rectangle(db.getLocation().x+10,db.getLocation().y+70,db.getWidth()-20,db.getHeight()-80);
	BufferedImage im=  ro.createScreenCapture(rt);
	

1.文件头信息

int bheadlen=14;
	//创建一个byte数组保存文件头信息
	byte[] bhead=new byte[bheadlen];
	bhead[0]='B';
	bhead[1]='M';
	//文件大小
	filesize=im.getWidth()*im.getHeight()*3;
	for(int i=2,j=0;i<6;i++,j++){
		byte[] by=change(filesize);
		bhead[i]=by[j];
	}
	//偏移量
	bfOffBits=54;
	for(int i=10,j=0;i<14;i++,j++){
		byte[] by=change(bfOffBits);
		bhead[i]=by[j];
	}
		dos.write(bhead);

2.位图信息

//保存位图信息的数组
	byte[] bmess=new byte[40];
	width=im.getWidth();
	high=im.getHeight();
	//本结构所占用字节数
	sss=40;
	for(int i=0,j=0;i<4;i++,j++){
		byte[] by=change(sss);
		bmess[i]=by[j];
	}
	for(int i=4,j=0;i<8;i++,j++){
		byte[] by=change(width);
		bmess[i]=by[j];
		}
	for(int i=8,j=0;i<12;i++,j++){
		byte[] by=change(high);
		bmess[i]=by[j];
	}
	//目标设备的级别,必须为1
	plane=1;
	bmess[12]=(byte) ((plane>>>0)&0xff);
	bmess[13]=(byte)((plane>>>8)&0xff);
	//每个像素所需的位数(此处为24真彩色)
	weishu=24;
	bmess[14]=(byte) ((weishu>>>0)&0xff);
	bmess[15]=(byte)((weishu>>>8)&0xff);
	//位图的大小
	weitusize=filesize-54;
	for(int i=20,j=0;i<24;i++,j++){
		byte[] by=change(weitusize);
		bmess[i]=by[j];
	}
	dos.write(bmess);

3.位图数据

//用于补0的数组
	byte d[]=new byte[rt.width%4];
	//写入位图数据
	for(int i=rt.height-1;i>=0;i--){					   
		for(int j=0;j<rt.width;j++){
			int rgb=im.getRGB(j, i);
			b[0]=(byte)rgb;
			rgb=rgb>>8;
			b[1]=(byte)rgb;
			rgb=rgb>>8;
			b[2]=(byte)rgb;
			dos.write(b); 
			if(rt.width%4!=0){
				dos.write(d);
			}
		}  
	}

这样呢就将自己画的图像保存到文件中去了!而且可以用自己写的bmp图形解析器打开哦! 赶快去试试吧

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。