BMP width & height, FileStream Learn programming Java



Lesson:

File Management


Exercise:

BMP width & height, FileStream


Objetive:

Create a java program to display the width and height of a BMP file using a FileStream.

Remember the structure of the BMP header:

File type (letters BM)
0-1

File Size
2-5

Reserved
6-7

Reserved
8-9

Start of image data
10-13

Size of bitmap header
14-17

Width (pixels)
18-21

Height (pixels)
22-25

Number of planes
26-27

Size of each point
28-29

Compression (0=not compressed)
30-33

Image size
34-37

Horizontal resolution
38-41

Vertical resolution
42-45

Size of color table
46-49

Important colors counter
50-53


Code:

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		FileStream myFile;
		byte[] data;
		int width, height;
		final int SIZE = 54;

		System.out.print("Enter the name of file: ");
		String fileName = new Scanner(System.in).nextLine();

		if (!(new java.io.File(fileName)).isFile())
		{
			System.out.println("The file not exists!!!");
			return;
		}

		try
		{
			myFile = File.OpenRead(fileName);
			data = new byte[SIZE];
			myFile.Read(data, 0, SIZE);
			myFile.Close();

			byte b1 = data[0];
			byte b2 = data[1];

			if (((char)b1 != 'B') || ((char)b2 != 'M'))
			{
				System.out.println("This File is NOT a BMP file");
				return;
			}

			width = data[18] + (data[19] * 256) + (data[20] * 256 * 256) + (data[21] * 256 * 256 * 256);

			height = data[22] + (data[23] * 256) + (data[24] * 256 * 256) + (data[25] * 256 * 256 * 256);

			System.out.printf("Width: %1$s - Heigth: %2$s" + "\r\n", width, height);
		}
		catch (RuntimeException e)
		{
			System.out.printf("Error: %1$s!!!" + "\r\n", e.message());
		}
	}
}



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.