Create a program in Java to read the dimensions of an image in Windows bitmap format. You should first check that it is a valid .bmp image, reviewing the header data ''BM''. If it is a valid .bmp image then it obtained its dimensions (width x height) and display them on the screen.
It is a format of the Windows operating system. You can save images up to 24 bits (16.7 million colors).
The header of a BMP image is as follows:
48x48
import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ReadBMPImageDimensions { public static void main(String[] args) { String fileName = "logo.bmp"; int headerSize = 54; int width = 0, height = 0; try (FileInputStream fileStream = new FileInputStream(fileName)) { byte[] headerData = new byte[headerSize]; fileStream.read(headerData, 0, headerSize); if (headerData[0] == 'B' && headerData[1] == 'M') { width = bytesToInt(headerData, 18, 22); height = bytesToInt(headerData, 22, 26); System.out.println(width + "x" + height); } else { System.out.println("Not a valid BMP file."); } } catch (IOException e) { e.printStackTrace(); } } private static int bytesToInt(byte[] bytes, int start, int end) { int result = 0; for (int i = end - 1; i >= start; i--) { result = (result << 8) | (bytes[i] & 0xFF); } return result; } }
Click here to view the exercise solution
Share it on your social media and challenge your friends to solve programming problems. Together, we can learn and grow.
The code has been successfully copied to the clipboard.
Continue improving your Java programming skills with our selection of practical exercises from the lesson. Click on Practice and challenge your knowledge!
Create a Java program that reads ID3 v1 specification tags from an MP3 music file.
Create a program in Java to read the dimensions of an image in Windows bitmap format.
Create a program in Java to encrypt an image in Windows bitmap format.
Create a program in Java that inverts all the bytes of a binary file.
Create a Java program that makes copies of both text and binary files.
Create a Java program that divides text or binary files into parts of 5 Kb each.
Create a hexadecimal viewer in Java that shows the contents of a binary file on screen as follows.
Practice with exercises in Java to manage binary files. Learn how to create, update, and search binary files in different ways.
Free programming course with practical exercises and solutions in C#. Start learning right now!
Take your Exercises C# lessons everywhere with our Android app. Download it now from Google Play
Own and third party cookies to improve our services. If you go on surfing, we will consider you accepting its use.