Java reads BMP Images

Source: Internet
Author: User

Basic Objective
A Windows BMP file is a common image format that Java does not handle. while BMP images are used only on Windows machines, they are reasonably common. reading these shows how to read complex structures in Java and
How to alter they byte order from the big endian order used by Java to the little endian order used by the windows and the intel processor.

--------------------------------------------------------
//
// This code was taken and cleaned up from
// Javaworld tips and tricks Column
//

Import java. AWT. image;
Import java. AWT. toolkit;
Import java. AWT. image. memoryimagesource;
Import java. Io. fileinputstream;
Import java. Io. ioexception;

Import javax. Swing. imageicon;
Import javax. Swing. jframe;
Import javax. Swing. jlabel;
Import javax. swing. JScrollPane;

//
// Really just a collection of methods to read a BMP file
//

Public class BMP Loader

{

// Build an int from a byte array-convert little to big endian
Public static int constructInt (byte [] in, int offset ){

Int ret = (int) in [offset + 3] & 0xff );

Ret = (ret <8) | (int) in [offset + 2] & 0xff );

Ret = (ret <8) | (int) in [offset + 1] & 0xff );

Ret = (ret <8) | (int) in [offset + 0] & 0xff );

Return (ret );

}

// Build an int from a byte array-convert little to big endian
// Set high order bytes to 0 xfff
Public static int constructInt3 (byte [] in, int offset ){

Int ret = 0xff;

Ret = (ret <8) | (int) in [offset + 2] & 0xff );

Ret = (ret <8) | (int) in [offset + 1] & 0xff );

Ret = (ret <8) | (int) in [offset + 0] & 0xff );

Return (ret );

}

// Build an int from a byte array-convert little to big endian
Public static long constructLong (byte [] in, int offset ){

Long ret = (long) in [Offset + 7] & 0xff );

RET | = (Ret <8) | (long) in [Offset + 6] & 0xff );

RET | = (Ret <8) | (long) in [Offset + 5] & 0xff );

RET | = (Ret <8) | (long) in [Offset + 4] & 0xff );

RET | = (Ret <8) | (long) in [Offset + 3] & 0xff );

RET | = (Ret <8) | (long) in [Offset + 2] & 0xff );

RET | = (Ret <8) | (long) in [Offset + 1] & 0xff );

RET | = (Ret <8) | (long) in [Offset + 0] & 0xff );

Return (RET );

}

// Build an double from a byte array-convert little to big endian
Public static double constructdouble (byte [] In, int offset ){

Long ret = constructlong (in, offset );

Return (double. longbitstodouble (RET ));

}

// Build an short from a byte array-convert little to big endian
Public static short constructshort (byte [] In, int offset ){

Short ret = (short) in [Offset + 1] & 0xff );

Ret = (short) (Ret <8) | (short) in [Offset + 0] & 0xff ));

Return (ret );

}

// Internal class representing a bitmap header structure
// With code to read it from a file
Static class BitmapHeader {

Public int nsize;

Public int nbisize;

Public int nwidth;

Public int nheight;

Public int nplanes;

Public int nbitcount;

Public int ncompression;

Public int nsizeimage;

Public int nxpm;

Public int nypm;

Public int nclrused;

Public int nclrimp;

// Read in the bitmap header
Public void read (FileInputStream fs) throws IOException

{

Final int bflen = 14; // 14 byte BITMAPFILEHEADER

Byte bf [] = new byte [bflen];

Fs. read (bf, 0, bflen );

Final int bilen = 40; // 40-byte BITMAPINFOHEADER

Byte bi [] = new byte [bilen];

Fs. read (bi, 0, bilen );

// Interperet data.
Nsize = constructInt (bf, 2 );

// System. out. println ("File type is:" + (char) bf [0] + (char) bf [1]);
// System. out. println ("Size of file is:" + nsize );

Nbisize = constructInt (bi, 2 );

// System. Out. println ("size of bitmapinfoheader is:" + nbisize );

Nwidth = constructint (Bi, 4 );

// System. Out. println ("width is:" + nwidth );

Nheight = constructint (Bi, 8 );

// System. Out. println ("height is:" + nheight );

Nplanes = constructshort (Bi, 12); // (INT) Bi [13] & 0xff) <8) |
// (INT) Bi [12] & 0xff;

// System. out. println ("Planes is:" + nplanes );

Nbitcount = constructShort (bi, 14); // (int) bi [15] & 0xff) <8) |
// (Int) bi [14] & 0xff;

// System. out. println ("BitCount is:" + nbitcount );

// Look for non-zero values to indicate compression
Ncompression = constructInt (bi, 16 );

// System. out. println ("Compression is:" + ncompression );

Nsizeimage = constructInt (bi, 20 );

// System. out. println ("SizeImage is:" + nsizeimage );

Nxpm = constructInt (bi, 24 );

// System. out. println ("X-Pixels per meter is:" + nxpm );

Nypm = constructInt (bi, 28 );

// System. out. println ("Y-Pixels per meter is:" + nypm );

Nclrused = constructInt (bi, 32 );

// System. out. println ("Colors used are:" + nclrused );

Nclrimp = constructInt (bi, 36 );

// System. out. println ("Colors important are:" + nclrimp );

}

}

Public static Image read (FileInputStream fs)

{

Try {

BitmapHeader bh = new BitmapHeader ();

Bh. read (fs );

If (bh. nbitcount = 24)

Return (readMap24 (fs, bh ));

If (bh. nbitcount = 32)

Return (readMap32 (fs, bh ));

If (bh. nbitcount = 8)

Return (readMap8 (fs, bh ));

Fs. close ();

} Catch (IOException e ){

// System. out. println ("Caught exception in loadbitmap! ");
}

Return (null );

}

/**
*
* ReadMap24 internal routine to read the bytes in a 24-bit bitmap
*
*
*
* Arguments:
*
* Fs-file stream
*
* Bh-header struct
*
* Returns:
*
* Image Object, be sure to check for (Image) null !!!!
*
*
*
*/
Protected static Image readMap32 (FileInputStream fs, BitmapHeader bh)
Throws IOException

{

Image image;

// No Palatte data for 24-bit format but scan lines are

// Padded out to even 4-byte boundaries.

Int xwidth = bh. nsizeimage/bh. nheight;

Int ndata [] = new int [bh. nheight * bh. nwidth];

Byte brgb [] = new byte [bh. nwidth * 4 * bh. nheight];

Fs. read (brgb, 0, bh. nwidth * 4 * bh. nheight );

Int nindex = 0;

For (int j = 0; j <bh. nheight; j ++)

{

For (int I = 0; I <bh. nwidth; I ++)

{

Ndata [bh. nwidth * (bh. nheight-j-1) + I] = constructInt3 (
Brgb, nindex );

Nindex + = 4;

}

}

Image = Toolkit. getdefatooltoolkit (). createImage

(New MemoryImageSource (bh. nwidth, bh. nheight,

Ndata, 0, bh. nwidth ));

Fs. close ();

Return (image );

}

/**
*
* ReadMap24 internal routine to read the bytes in a 24-bit bitmap
*
*
*
* Arguments:
*
* Fs-file stream
*
* Bh-header struct
*
* Returns:
*
* Image Object, be sure to check for (Image) null !!!!
*
*
*
*/
Protected static Image readMap24 (FileInputStream fs, BitmapHeader bh)
Throws IOException

{

Image image;

// No Palatte data for 24-bit format but scan lines are

// Padded out to even 4-byte boundaries.

Int npad = (bh. nsizeimage/bh. nheight)-bh. nwidth * 3;

Int ndata [] = new int [bh. nheight * bh. nwidth];

Byte brgb [] = new byte [(bh. nwidth + npad) * 3 * bh. nheight];

Fs. read (brgb, 0, (bh. nwidth + npad) * 3 * bh. nheight );

Int nindex = 0;

For (int j = 0; j <bh. nheight; j ++)

{

For (int I = 0; I <bh. nwidth; I ++)

{

Ndata [bh. nwidth * (bh. nheight-j-1) + I] = constructInt3 (
Brgb, nindex );

Nindex + = 3;

}

Nindex + = npad;

}

Image = Toolkit. getdefatooltoolkit (). createImage

(New MemoryImageSource (bh. nwidth, bh. nheight,

Ndata, 0, bh. nwidth ));

Fs. close ();

Return (image );

}

/**
*
* Readmap8 internal routine to read the bytes in a 8-Bit Bitmap
*
*
*
* Arguments:
*
* FS-file stream
*
* Bh-header struct
*
* Returns:
*
* Image object, be sure to check for (image) null !!!!
*
*
*
*/
Protected static image readmap8 (fileinputstream FS, bitmapheader BH)
Throws ioexception

{

Image image;

// Have to determine the number of colors, the clrsused

// Parameter is dominant if it is greater than zero. If

// Zero, calculate colors based on bitsperpixel.

Int nnumcolors = 0;

If (bH. nclrused> 0)

{

NNumColors = bh. nclrused;

}

Else

{

NNumColors = (1 & 0xff) <bh. nbitcount;

}

// System. out. println ("The number of Colors is" + nNumColors );

// Some bitmaps do not have the sizeimage field calculated

// Ferret out these cases and fix 'em.

If (bh. nsizeimage = 0)

{

Bh. nsizeimage = (bh. nwidth * bh. nbitcount) + 31 )&~ 31)> 3 );

Bh. nsizeimage * = bh. nheight;

// System. out. println ("nsizeimage (backup) is" + nsizeimage );

}

// Read the palatte colors.

Int npalette [] = new int [nNumColors];

Byte bpalette [] = new byte [nNumColors * 4];

Fs. read (bpalette, 0, nNumColors * 4 );

Int nindex8 = 0;

For (int n = 0; n <nNumColors; n ++)

{

Npalette [n] = constructInt3 (bpalette, nindex8 );

Nindex8 + = 4;

}

// Read the image data (actually indices into the palette)

// Scan lines are still padded out to even 4-byte

// Boundaries.

Int npad8 = (bh. nsizeimage/bh. nheight)-bh. nwidth;

// System. out. println ("nPad is:" + npad8 );

Int ndata8 [] = new int [bh. nwidth * bh. nheight];

Byte bdata [] = new byte [(bh. nwidth + npad8) * bh. nheight];

Fs. read (bdata, 0, (bh. nwidth + npad8) * bh. nheight );

Nindex8 = 0;

For (int j8 = 0; j8 <bh. nheight; j8 ++)

{

For (int i8 = 0; i8 <bh. nwidth; i8 ++)

{

Ndata8 [bh. nwidth * (bh. nheight-j8-1) + i8] =

Npalette [(int) bdata [nindex8] & 0xff)];

Nindex8 ++;

}

Nindex8 + = npad8;

}

Image = Toolkit. getdefatooltoolkit (). createImage

(New MemoryImageSource (bh. nwidth, bh. nheight,

Ndata8, 0, bh. nwidth ));

Return (image );

}

/**
*
* Load method-see read for details
*
*
*
* Arguments:
*
* Sdir and sfile are the result of the filedialog ()
*
* Getdirectory () and GetFile () methods.
*
*
*
* Returns:
*
* Image object, be sure to check for (image) null !!!!
*
*
*
*/
Public static Image load (String sdir, String sfile ){

Return (load (sdir + sfile ));

}

/**
*
* Load method-see read for details
*
*
*
* Arguments:
*
* Sdir-full path name
*
*
*
* Returns:
*
* Image Object, be sure to check for (Image) null !!!!
*
*
*
*/
Public static Image load (String sdir)

{

Try

{

FileInputStream fs = new FileInputStream (sdir );

Return (read (fs ));

}

Catch (IOException ex ){

Return (null );

}

}

Public static void main (string [] ARGs) throws ioexception

{

If (ARGs. Length = 0 ){

System. Out. println ("usage> java bmp loader imagefile.bmp ");

System. Exit (0 );

}

Fileinputstream in = new fileinputstream (ARGs [0]);

Image theimage = read (in );

JFrame TheFrame = new JFrame (args [0]);

JLabel TheLabel = new JLabel (new ImageIcon (TheImage ));

TheFrame. getContentPane (). add (new JScrollPane (TheLabel ));

TheFrame. setSize (300,300 );

TheFrame. setVisible (true );

}
// End class BMP Loader
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.