90°

PHP轮子之图片局部马赛克

<?php
class Mosaic {
    public function run() {
        $filename     = './image.jpg'; // 要被打马赛克的图片路径
        $saveFileName = './image_mosaic.jpg';// 打上马赛克后的保存名
        $x            = 300; // 起始位置的x
        $y            = 20; // 起始位置的y
        $width        = 100; // 马赛克区域的宽度
        $height       = 30; // 马赛克区域的高度
        list($src_w) = getimagesize($filename); // 原图片的宽度
        $image = imagecreatefromjpeg($filename);
        $deep  = $this->getDeep($src_w);
        if ($x <= $width && $y <= $height) {
            for ($i = $x; $i <= $width; $i += $deep) {
                for ($j = $y; $j <= $height; $j += $deep) {
                    $color = imagecolorat($image, $i + round($deep / 2), $j + round($deep / 2));
                    $rgb   = $this->getColor($color);
                    $col   = imagecolorallocatealpha($image, $rgb['r'], $rgb['g'], $rgb['b'], 0);
                    imagefilledrectangle($image, $i, $j, $i + $deep, $j + $deep, $col);
                }
            }
        } else {
            for ($i = 0; $i < $width; $i += $deep) {
                for ($j = 0; $j < $height; $j += $deep) {
                    $color = imagecolorat($image, $x + $i + round($deep / 2), $y + $j + round($deep / 2));
                    $rgb   = $this->getColor($color);
                    $col   = imagecolorallocatealpha($image, $rgb['r'], $rgb['g'], $rgb['b'], 0);
                    imagefilledrectangle($image, $x + $i, $y + $j, $x + $i + $deep, $y + $j + $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 &gt;&gt; 16) &amp; 0xFF;
    $g         = ($rgb &gt;&gt; 8) &amp; 0xFF;
    $b         = $rgb &amp; 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 =&gt; &amp;$value) {
        if ($value &lt; $cover) {
            $value = $cover;
        }
    }

    return $rgb;
}

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

} $mosaic = new Mosaic(); $mosaic->run();

 

本文由【YourExclusive】发布于开源中国,原文链接:https://my.oschina.net/colinadmin/blog/3158636

全部评论: 0

    我有话说: