JAVA读取BMP图片_以字节流读取BMP图像_从数据库读取图片
程序员文章站
2022-03-01 16:03:20
...
最近一直在搞图片上传这些问题、今天又找到一种新方法、记下来、方便以后使用
用字节流而不是用JAVA的API函数read()有助于大家理解理解BMP的存储方式哈
同时,如果是从数据库中读取图片的话,也是用字节流读取,需要自己进行转换的
所以这种方式更利于我们的使用、话不多说、直接为大家献上代码
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; }