Home > Backend Development > PHP Tutorial > How to use GD library in php to turn a square picture into a circular picture (code)

How to use GD library in php to turn a square picture into a circular picture (code)

不言
Release: 2023-04-03 20:20:02
Original
4804 people have browsed it

The content of this article is about the method (code) of using PHP to convert a square image into a circular image using the GD library. It has a certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.

When we get the WeChat avatar, we will find it is square when we grab it, but in reality we usually use circles.

Below I will introduce the use of PHP native GD library to capture the image and cut it into rounded corners. In fact, the code is very simple, so I will just upload the code.

<?php
    $path = "";//文件绝对路径
    $this->yuanjio($path);
     /*
     * 将图片切成圆角
     */
    public function yuanjiao($imgpath){
        $ext     = pathinfo($imgpath);
        $src_img = null;
        switch ($ext[&#39;extension&#39;]) {
            case &#39;jpg&#39;:
                $src_img = imagecreatefromjpeg($imgpath);
                break;
            case &#39;png&#39;:
                $src_img = imagecreatefrompng($imgpath);
                break;
        }
        $wh  = getimagesize($imgpath);
        $w   = $wh[0];
        $h   = $wh[1];
        $w   = min($w, $h);
        $h   = $w;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r   = $w / 2; //圆半径
        $y_x = $r; //圆心X坐标
        $y_y = $r; //圆心Y坐标
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
        return $img;
    }
Copy after login

Related recommendations:

Example of using GD library to create a circular pie chart in PHP, gd circle

Generate picture thumbnail class in PHP based on GD2 graphics library Code sharing,

The above is the detailed content of How to use GD library in php to turn a square picture into a circular picture (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template