// The DataInputStream allows you to read in 16 and 32 bit numbers DataInputStream in =new DataInputStream(instream); DataOutputStream out=new DataOutputStream(outstream); // Verify that the header starts with 'BM' if (in.read() !='B') { thrownew IOException("Not a .BMP file"); } out.write('B'); if (in.read() !='M') { thrownew IOException("Not a .BMP file"); } out.write('M'); // Get the total file size int fileSize = intelInt(in.readInt()); out.writeInt(intelInt(fileSize)); // Skip the 2 16-bit reserved words out.writeShort(in.readUnsignedShort()); out.writeShort(in.readUnsignedShort()); int bitmapOffset = intelInt(in.readInt()); out.writeInt(intelInt(bitmapOffset)); int bitmapInfoSize = intelInt(in.readInt()); out.writeInt(intelInt(bitmapInfoSize)); int width = intelInt(in.readInt()); out.writeInt(intelInt(width)); int height = intelInt(in.readInt()); out.writeInt(intelInt(height)); // Skip the 16-bit bitplane size out.writeShort(in.readUnsignedShort()); int bitCount = intelShort(in.readUnsignedShort()); out.writeShort(intelShort(bitCount)); int compressionType = intelInt(in.readInt()); out.writeInt(intelInt(compressionType)); int imageSize = intelInt(in.readInt()); out.writeInt(intelInt(imageSize)); // Skip pixels per meter out.writeInt(in.readInt()); out.writeInt(in.readInt()); int colorsUsed = intelInt(in.readInt()); out.writeInt(intelInt(colorsUsed)); int colorsImportant = intelInt(in.readInt()); out.writeInt(intelInt(colorsImportant)); System.out.println("[colorused]="+colorsUsed); // Read the pixels from the stream based on the compression type if (compressionType == BI_RGB) { if (bitCount ==24) { readRGB24(width, height, in, out); } } }
protectedstaticvoid readRGB24(int width, int height, DataInputStream in, OutputStream out) throws IOException { // Start storing at the bottom of the array for (int h = height-1; h >=0; h--) { for (int w =0; w < width; w++) { // Read in the red, green, and blue components int red = in.read(); int green = in.read(); int blue = in.read(); out.write(red); out.write(green); out.write(blue); } } }