PHP轮子之图片局部马赛克

深渊向深渊呼唤
<?php
class Mosaic {
    public function run() {
        $filename     = './image.jpg'; // 要被打马赛克的图片路径
        $saveFileName = './image_mosaic.jpg';// 打上马赛克后的保存名
        $x            = 200; // 起始位置的x
        $y            = 20; // 起始位置的y
        $width        = 100; // 马赛克区域的宽度
        $height       = 30; // 马赛克区域的高度
        list($src_w) = getimagesize($filename); // 原图片的宽度
        $image = imagecreatefromjpeg($filename);
        $deep  = $this->getDeep($src_w);
        for ($i = 0; $i < $width; $i += $deep) {
            for ($j = 0; $j < $height; $j += $deep) {
                $calcX = $x + $i;
                $calcY = $y + $j;
                $color = imagecolorat($image, $calcX + round($deep / 2), $calcY + round($deep / 2));
                $rgb   = $this->getColor($color);
                $col   = imagecolorallocatealpha($image, $rgb['r'], $rgb['g'], $rgb['b'], 0);
                imagefilledrectangle($image, $calcX, $calcY, $calcX + $deep, $calcY + $deep, $col);
            }
        }
        imagejpeg($image, $saveFileName);
        imagedestroy($image);
    }

    /**
     * 获取颜色RGBA
     *
     * @param int $rgb 颜色值
     *
     * @return array
     */
    protected function getColor(int $rgb) {
        $rColorNum = $gColorNum = $bColorNum = $total = 0;
        //三通道
        $r         = ($rgb >> 16) & 0xFF;
        $g         = ($rgb >> 8) & 0xFF;
        $b         = $rgb & 0xFF;
        $rColorNum += $r;
        $gColorNum += $g;
        $bColorNum += $b;
        $total++;
        $rgb      = [];
        $rgb['r'] = round($rColorNum / $total);
        $rgb['g'] = round($gColorNum / $total);
        $rgb['b'] = round($bColorNum / $total);
        // 替换比较黑的颜色值,让比较黑的颜色变淡
        $cover = 104; // 替换为#686868
        foreach ($rgb as $key => &$value) {
            if ($value < $cover) {
                $value = $cover;
            }
        }

        return $rgb;
    }

    /**
     * 根据图片长度计算马赛克框大小
     *
     * @param int $width 图片的长度
     *
     * @return int
     */
    protected function getDeep(int $width) {
        switch (true) {
            case $width >= 3000 :
                return 30;
            case $width >= 2000 :
                return 20;
            case $width >= 1000 :
                return 10;
            case $width >= 100 :
                return 5;
        }
    }
}
$mosaic = new Mosaic();
$mosaic->run();

 

栏目