Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP和ImageMagick以编程方式将RGB图像转换为1位灰度(b/w)位图图像_Php_Bitmap_Imagemagick_Rgb_Grayscale - Fatal编程技术网

使用PHP和ImageMagick以编程方式将RGB图像转换为1位灰度(b/w)位图图像

使用PHP和ImageMagick以编程方式将RGB图像转换为1位灰度(b/w)位图图像,php,bitmap,imagemagick,rgb,grayscale,Php,Bitmap,Imagemagick,Rgb,Grayscale,我正在尝试使用PHP(版本:5.2.13)和ImageMagick(版本:6.7.8-7-Q16)以编程方式将位图RGB图像转换为1位灰度(b/w)位图图像。输入图像为位图,通过ImageMagick函数生成: bool Imagick::setFormat ( string $format ) 其中$format='bmp2' 以下代码在过去曾经有效(ImageMagick的旧版本…不记得是哪一个),但在当前环境中不再有效: private function monochrome() {

我正在尝试使用PHP(版本:5.2.13)和ImageMagick(版本:6.7.8-7-Q16)以编程方式将位图RGB图像转换为1位灰度(b/w)位图图像。输入图像为位图,通过ImageMagick函数生成:

bool Imagick::setFormat ( string $format )
其中$format='bmp2'

以下代码在过去曾经有效(ImageMagick的旧版本…不记得是哪一个),但在当前环境中不再有效:

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");
    }
}
问题是生成的图像仍在RGB颜色空间中

我还尝试:

$this->image->setImageColorSpace(Imagick::COLORSPACE_GRAY);
但结果并没有改变

我的目标是为签名捕获应用程序生成尽可能最小的黑白位图图像。我知道有比位图更好的图像格式,但生成的图像必须与旧的Access 97兼容。这就是为什么“bmp2”是图像格式的选择

有什么想法吗?谢谢

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

这个示例是用perl编写的,您可以轻松地将其转换为php…

我只做了这个,它创建了一个黑白图像:

$im = new Imagick();
$im->readimage($filename);
$im->resizeimage($width, $height, Imagick::FILTER_UNDEFINED, 1, false);
$im->posterizeimage(2, false);
$im->writeimage($filename.".bmp");
它会创建一个标识如下的图像:

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

2c表示它只包含2个巨像,但图像没有颜色索引表。

您建议的(量化)就是我的代码所做的。设置分辨率没有任何帮助。对我来说,这段代码工作得很好,可能你还有其他问题,请尝试使用不同的图像。非常感谢!posterizeimage(2,false)像冠军一样工作。最后,经过将近一年的时间,我终于让代码正常工作了!不客气,我已经用它来处理冲压硬件了。我也在.Net上实现了这段代码,并用mono运行了它,但在将位图保存到内存时失败了很多。@carlos-c-soto建议的解决方案非常有效。我只需要将:quantizeImage(2,Imagick::COLORSPACE_GRAY,5,false,true)替换为:posterizeimage(2,false)