PHP扫描图片转点阵 二维码转点阵

	/**
     * 图片转点阵(黑白)
     * @param string $imgPath
     * @return array
     */
    function imgToLattice(string $imgPath): array
    {
        $size = getimagesize($imgPath);// 得到图片的信息
        $im = imagecreatefrompng($imgPath);// 創建一張圖片
        // 储存二进制数组
        $lattice = [];
        $white = [
            'red' => 255,
            'green' => 255,
            'blue' => 255,
            'alpha' => 0,
        ];
        for ($i = 0; $i < $size[1]; ++ $i) {
            $lattice[$i] = '';
            for ($j = 0; $j < $size[0]; ++$j) {
                $rgb = imagecolorat($im, $j, $i);          //取得某像素的颜色索引值
                $rgbArr = imagecolorsforindex($im, $rgb);
                if ($white === $rgbArr){
                    $lattice[$i] .= 0;
                }else{
                    $lattice[$i] .= 1;
                }
            }
        }

        return [$lattice, $size];
    }

注解:

$rgbArr = imagecolorsforindex($im, $rgb);

这里返回一个RGB数组,跟$white数组一样,我因为二维码只有黑白,所以这里只做了黑白判断,黑就是1,白就是0,如果你的图片支持三种级以上,这里可以做判断,拼接其他数字

if ($white === $rgbArr){
	$lattice[$i] .= 0;
}else{
	$lattice[$i] .= 1;
}

打印出来效果:

转成HTML:

原文地址:https://www.cnblogs.com/cxfs/p/13461965.html