Exercises Java with Examples-
Practice Exercises Java 4,5 5 302940

BMP width & height, FileStream - Practice Exercises Java


Lesson 8:

File management


Exercise 8.24:

BMP width & height, FileStream


Objetive:

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

Remember the structure of the header:

File type (letters BM)
0-1

FileSize
2-5

Reserved
6-7

Reserved
8-9

Start of image data
10-13

Sizeofbitmapheader
14-17

Width (pixels)
18-21

Height (pixels)
22-25

Numberofplanes
26-27

Sizeofeachpoint
28-29

Compression(0=notcompressed)
30-33

Imagesize
34-37

Horizontal resolution
38-41

Verticalresolution
42-45

Sizeofcolortable
46-49

Importantcolorscounter
50-53


Source 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());
		}
	}
}
Exercisey 8.24

Share Now:


Google Ads





Privacy Policy:



Google uses associated advertising companies to serve ads when it visits our website. These companies may use the information they obtain from your visits to this and other websites (not including your name, address, email address, or phone number) to provide you with announcements about products and services that interest you. If you would like to learn more about this practice and know your options to prevent these companies from using this information. Click in... Privacy and Terms of Google.

Cookies

This site uses Google cookies to provide its services, to personalize advertisements and to analyze traffic. Google receives information about your use of this website. More information in... Privacy and Terms of Google.