简体   繁体   中英

Programmatically convert RGB image to 1-bit Grayscale (b/w) bitmap image with PHP and ImageMagick

I'm trying to programmatically convert a bitmap RGB image to 1-bit Grayscale (b/w) bitmap image using PHP (version: 5.2.13) and ImageMagick (version: 6.7.8-7-Q16). The input image is bitmap and is generated by means of the ImageMagick function:

bool Imagick::setFormat ( string $format )

where $format = 'bmp2'

The following code used to work in the past (older version of ImageMagick... don't remember which one), but it's not working anymore in the current environment:

private function monochrome() {
    if (isset($this->image)) {
        try {
            // reduce image colors to 2 (black and white)
            $this->image->quantizeImage(2, Imagick::COLORSPACE_GRAY, 5, false, true);

            // reduce image depth to 1 bit per pixel
            $this->image->setImageDepth(1);
            $this->image->setImageChannelDepth(Imagick::CHANNEL_ALL, 1);

            // set image type to monochrome (2 colors: black and white only)
            $this->image->setImageType(Imagick::IMGTYPE_BILEVEL);
        }
        catch (ImagickException $ie) {
            throw $ie;
        }
    }
    else {
        throw new Exception("No image object");
    }
}

The problem is that the image produced is still in the RGB color space.

I also tried:

$this->image->setImageColorSpace(Imagick::COLORSPACE_GRAY);

but the result does not change.

My goal is to generate the smallest possible, black and white, bitmap image for a signature capture application. I know there are better image formats than bitmap, but the generated image has to be compatible with the old Access 97. That is why 'bmp2' is the choice for the image format.

Any ideas? Thanks!

I only make this and it creates a B/W image:

$im = new Imagick();
$im->readimage($filename);
$im->resizeimage($width, $height, Imagick::FILTER_UNDEFINED, 1, false);
$im->posterizeimage(2, false);
$im->writeimage($filename.".bmp");

It creates an image identified like:

$ identify example.png.bmp 
example.png.bmp BMP 1742x236 1742x236+0+0 1-bit PseudoClass 2c 52.1KB 0.000u 0:00.000

The 2c says that it only contains 2 colos, but hte image does not have an indexed table of colors.

    my $image = Image::Magick->new;
    $image->Read($imagePath);
    $image->Quantize(colorspace=>"gray"):
    $image->Set(density => '72x72');

This example is written in perl, you can easily convert it to php...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM