Show BMP on console - Python Programming Exercise

In this exercise, you will develop a Python program to decode and display a Netpbm image file. This exercise is perfect for practicing file handling, string manipulation, and loops in Python. By implementing this program, you will gain hands-on experience in handling file operations, string manipulation, and loops in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 Exercise

Show BMP On Console

 Objective

Develop Python program to decode and display a Netpbm image file

The Netpbm format is a family of image formats designed for simplicity rather than file size. These formats can represent color, grayscale, or black-and-white images using plain text, although binary versions also exist.

For instance, a black-and-white image encoded in ASCII uses the "P1" header.

The file may optionally contain a comment line starting with #.

Next, the image dimensions (width and height) are listed on the following line.

The remaining lines contain the pixel data: 1 represents black and 0 represents white. For example:

P1
This is an example bitmap of the letter "J"
6 10
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
1 0 0 0 1 0
0 1 1 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0

Create a Python program to decode this type of image file and display its content in the console. Note that the comment is optional.

 Example Python Exercise

 Copy Python Code
# Python program to decode and display a Netpbm image (P1 format) from a file

def decode_netpbm(file_path):
    try:
        # Open the Netpbm file
        with open(file_path, 'r') as file:
            # Read the first line (P1 header)
            header = file.readline().strip()
            if header != 'P1':
                print("Error: This is not a valid P1 Netpbm image.")
                return
            
            # Skip comment lines (if present)
            while True:
                line = file.readline().strip()
                if line and not line.startswith('#'):
                    # This is the line with image dimensions (width and height)
                    width, height = map(int, line.split())
                    break
            
            # Read and display the pixel data
            print(f"Image dimensions: {width}x{height}")
            print("Image Data:")
            for _ in range(height):
                row = file.readline().strip().split()
                # Convert 0 to 'White' and 1 to 'Black' and display it
                print(' '.join('Black' if pixel == '1' else 'White' for pixel in row))
    
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
    except Exception as e:
        print(f"Error: {str(e)}")

# Example usage
decode_netpbm('image.pbm')

 Output

Example Input (image.pbm):

P1
# This is an example bitmap of the letter "J"
6 10
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
1 0 0 0 1 0
0 1 1 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0

Example Output:

Image dimensions: 6x10
Image Data:
White White White White Black White
White White White White Black White
White White White White Black White
White White White White Black White
White White White White Black White
White White White White Black White
Black White White White Black White
White Black Black Black White White
White White White White White White
White White White White White White

 Share this Python Exercise

 More Python Programming Exercises of Managing Files

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Extract Text Information from a Binary File

    In this exercise, you will develop a Python program to extract only the alphabetic characters contained in a binary file and dump them into a separate file. This e...

  •  Dump

    In this exercise, you will develop a Python program to create a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes in each row and 24 ro...

  •  Text Filter

    In this exercise, you will develop a Python program to create a utility that censors text files. This exercise is perfect for practicing file handling, string ...

  •  SQL to Plain Text

    In this exercise, you will develop a Python program to parse SQL INSERT commands and extract their data into separate lines of text. This exercise is perfect f...

  •  PGM Image Viewer

    In this exercise, you will develop a Python program to create a utility that reads and displays images in the PGM format, which is a version of the NetPBM image forma...

  •  Console BMP Viewer V2

    In this exercise, you will develop a Python program to create a utility that displays a 72x24 BMP file on the console. This exercise is perfect for practicing ...