用字节流而不是用JAVA的API函数read()有助于大家理解理解BMP的存储方式哈。
同时,从SQL中读取图片的话,也是用字节流读取,需要自己进行转换的。
顺便保存下代码。。。下次用就有模板了。。。
只有24位图的哈。
public Image myRead(String path) throws java.io.IOException {
Image image = null;
int biWidth,biHeight,bicount,biSizeImage,npad,head,information,size;
try {
FileInputStream fs = new FileInputStream(path);
head = 14;
/**
* head is 14bytes;
*/
byte header[] = new byte[head];
fs.read(header, 0, head);
information = 40;
/**
* information is 40bytes;
*/
byte info[] = new byte[information];
fs.read(info, 0, information);
/**
* get the wideth of the bmp
*/
biWidth = ((int)(info[7]&toDec))<<24
| ((int)(info[6]&toDec))<<16
| ((int)(info[5]&toDec)) << 8
| ((int)(info[4]&toDec));
/**
* get the heigth of the bmp
*/
biHeight = ((int)(info[11]&toDec))<<24
| ((int)(info[10]&toDec))<<16
| ((int)(info[9]&toDec)) << 8
| ((int)(info[8]&toDec));
bicount = (((int)info[15] & toDec) << 8)
| (int)info[14] & toDec;
/**
* get the size of the image
*/
biSizeImage = ((int)(info[23]&toDec))<<24
| ((int)(info[22]&toDec))<<16
| ((int)(info[21]&toDec)) << 8
| ((int)(info[20]&toDec));
if (bicount == 24) {
/**
* compute the empty byte
*/
npad = (biSizeImage / biHeight) - biWidth*3;
/**
* if the BitCount is 24, every pixel has 3
*/
if (npad ==4 ) {
npad = 0;
}
/* compute the size of pixel */
size = (biWidth + npad) * 3 *biHeight;
byte alRgb[];
if (npad != 0) {
/**
* creat a array to save RGB data
*/
alRgb = new byte[(biWidth + npad) * 3 *biHeight];
} else {
/**
* creat a array to save RGB data
*/
alRgb = new byte[biSizeImage];
}
/* read all rgb data */
fs.read(alRgb, 0 , size);
int rgbData[] = new int[biHeight*biWidth];
/* translate hexadecimal data to decimal data */
int nindex = 0;
for(int j = 0; j < biHeight; j++){
for(int i = 0; i < biWidth; i++){
rgbData[biWidth * (biHeight - j - 1) + i] =
(255 & 0xff) << 24
| (((int)alRgb[nindex + 2] & 0xff) << 16)
| (((int)alRgb[nindex + 1] & 0xff) << 8)
| (int)alRgb[nindex] & 0xff;
nindex += 3;
}
nindex += npad;
}
/* creat image object */
image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(
biWidth, biHeight, rgbData, 0, biWidth));
}
fs.close();
} catch (IOException e) {
return null;
}
return image;
}
public Image myWrite(Image image, String file ) throws java.io.IOException {
try {
int w = image.getHeight(null);
int h = image.getWidth(null);
/**
* ceate graphic
*/
BufferedImage bi = new BufferedImage(w,h,BufferedImage.TYPE_3BYTE_BGR);
Graphics g = bi.getGraphics();
g.drawImage(image, 0, 0, null);
/* open file */
File iFile= new File(file+".bmp");
ImageIO.write(bi, "bmp", iFile);
} catch (IOException e) {
return null;
}
return image;
}