Current Location: Home> Latest Articles> How to Use the imagexbm Function to Create XBM Images? A Step-by-Step Guide to Generate Black and White Image Format

How to Use the imagexbm Function to Create XBM Images? A Step-by-Step Guide to Generate Black and White Image Format

gitbox 2025-09-20

<?php
/*
Article Title: How to Use the imagexbm Function to Create XBM Images? A Step-by-Step Guide to Generate Black and White Image Format
*/

// XBM is a black-and-white image format commonly used for embedded systems or early web icons. PHP provides the imagexbm() function, which can save GD image resources as XBM files. Below is a step-by-step guide on how to use it.

echo "

1. Create a Black-and-White Image Resource

";
echo "

First, you need to use PHP's GD library to create an image resource. XBM images can only be black and white, so you can create an image using imagecreatetruecolor(), then convert it to black and white.

"
;

// Create a 100x100 pixel image
$width = 100;
$height = 100;
$image = imagecreatetruecolor($width, $height);

// Fill the background with white
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, $width, $height, $white);

// Draw some black patterns
$black = imagecolorallocate($image, 0, 0, 0);
imageline($image, 10, 10, 90, 90, $black);
imagerectangle($image, 20, 20, 80, 80, $black);

echo "

2. Save the Image as an XBM File using imagexbm()

"
;
echo "

You can save the GD image resource as an XBM file using the imagexbm() function. The syntax of the function is as follows:

"
;
echo "
bool imagexbm ( resource $image , string $filename [, int $foreground = 0 ] )
"
;
echo "

Here, $foreground is the color index for black pixels, with a default value of 0.

"
;

// Save as an XBM file
$filename = 'example.xbm';
imagexbm($image, $filename);

// Free the image resource
imagedestroy($image);

echo "

The XBM image has been generated: $filename

";

echo "

3. Use the XBM Image in HTML

"
;
echo "

XBM files are commonly used as web icons or background images in CSS:

"
;
echo "
<br>
<img src='example.xbm' alt='XBM Image'><br>
"
;

echo "

4. Summary

"
;
echo "

Using PHP's imagexbm() function, you can quickly save black-and-white GD images as XBM format, suitable for embedded systems, vintage web icons, and other scenarios. The steps include:

"
;
echo "

  1. Create GD image resources (imagecreatetruecolor)
  2. Draw black-and-white graphics
  3. Save as an XBM file using imagexbm()
  4. Free the image resource
"
;
?>