1.BMP文件格式
BMP(Bitmap-File)图形文件是Windows采用的图形文件格式,在Windows环境下运行的所有图象处理软件 都支持BMP图 象文件格式。Windows系统内部各图像绘制操作都是以BMP为基础的。BMP位图文件默认的文件扩展名是BMP或者bmp(有 时它也会以.DIB或.RLE作扩展名)。
结构:
位图文件头、位图信息头、彩色表和定义位图的字节阵列。
2.首先设定文件保存和打开的方法
保存:
public boolean saveFile(String path,int [][] colors,JPanel panel){
boolean state = false;
try{
//创建流对象
FileOutputStream fos = new FileOutputStream(path);
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream dos = new DataOutputStream(bos);
//写入数据到文件
//获取宽度和高度
int width = panel.getWidth();
int height = panel.getHeight();
//先写入文件头部信息(宽和高)
dos.writeInt(width);
dos.writeInt(height);
//开始循环写入文件的内容部分
for(int i=0;i<width;i++){
for(int j=0;j<height;j++){
dos.writeInt(colors[i][j]);
}
}
dos.flush();
dos.close();
bos.close();
fos.close();
state = true;
}catch(Exception e){
e.printStackTrace();
}
return state;
}
BMP文件存储数据时,图像的扫描方式是按从左到右、从下到上的顺序
打开
public int[][] openFile(String path){
int [][] colors = null;
try{
//创建流对象
FileInputStream fis = new FileInputStream(path);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
//写入数据到文件
//获取宽度和高度
int width = dis.readInt();
int height = dis.readInt();
//实例化数组
colors = new int[width][height];
//开始循环写入文件的内容部分
for(int i=0;i<width;i++){
for(int j=0;j<height;j++){
colors[i][j] = dis.readInt();
}
}
dis.close();
bis.close();
fis.close();
}catch(Exception e){
e.printStackTrace();
}
return colors;
}
}
3.获取画图区域上的像素点
public static int [][] savePic(JPanel panel){
try {
//实例化Robot对象
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
//获取面板的宽度和高度
width = panel.getWidth();
height = panel.getHeight();
//获取面板的起始坐标
Point p = panel.getLocation();
//根据起始坐标、宽和高来截取一个矩形区域
Rectangle rect = new Rectangle(p.x,p.y,width,height);
//定义一个缓冲图片对象
BufferedImage image = robot.createScreenCapture(rect);
//实例化一个二维数组
colors = new int[width][height];
//循环遍历图片对象
for(int i=0;i<width;i++){
for(int j=0;j<height;j++){
colors[i][j] = image.getRGB(i, j);
}
}
return colors;
}
}