package bmpviewer.bmp; import java.io.*; /** * BMP image file writer *
* @author Hiroyuki Murata
* @since JDK1.1
*/
public class BmpWriter extends BmpHeader{
File file;
FileOutputStream fos;
RGBCounter counter;
int[] pix;
int wid,hei,rgbcount,rgbquadints,rgbquadbytes,widthbytes;
public BmpWriter(File file, int pix[], int wid, int hei) {
this.file = file;
this.pix = pix;
this.wid = wid;
this.hei = hei;
}
public void write() throws IOException {
counter = new RGBCounter(pix,256);
rgbCount();
widthbytes = ((wid * biBitCount + 31) & ~31) >>> 3;
rgbquadbytes = rgbquadints << 2;
bfOffBits = bf_size + bi_size + rgbquadbytes;
biSizeImage = widthbytes * hei;
bfSize = bfOffBits + biSizeImage;
fos = new FileOutputStream(file);
writeFileHeader();
writeInfoHeader();
writeRGBQuad();
writeBody();
fos.close();
}
void rgbCount() {
rgbcount = counter.count();
if (rgbcount < 0) { biBitCount = 24; rgbquadints = 0; }
else if (rgbcount > 16) { biBitCount = 8; rgbquadints = 256; }
else if (rgbcount > 2) { biBitCount = 4; rgbquadints = 16; }
else { biBitCount = 1; rgbquadints = 2; }
}
void writeFileHeader() throws IOException {
fileheader = new ByteArrayManipulator(bf_size,false);
fileheader.set2(0x4d42, pbfType);
fileheader.set4(bfSize, pbfSize);
fileheader.set4(bfOffBits, pbfOffBits);
fos.write(fileheader.getBytes());
}
void writeInfoHeader() throws IOException {
infoheader = new ByteArrayManipulator(bi_size,false);
infoheader.set4(bi_size, pbiSize);
infoheader.set4(wid, pbiWidth);
infoheader.set4(hei, pbiHeight);
infoheader.set2(1, pbiPlanes);
infoheader.set2(biBitCount, pbiBitCount);
infoheader.set4(biSizeImage,pbiSizeImage);
infoheader.set4(0x1000, pbiXPelsPerMeter);
infoheader.set4(0x1000, pbiYPelsPerMeter);
fos.write(infoheader.getBytes());
}
void writeRGBQuad() throws IOException {
int[] rgbquad = counter.getTable();
if (rgbquad == null)
return;
ByteArrayManipulator bamRgbQuad
= new ByteArrayManipulator(rgbquadbytes, false);
for (int i=0; i