php利用gd库将长方形图片转换成圆形

思路是创建一个和原图宽和高一样的画布(背景透明),然后获取原图片里面的一个圆形,最后再将圆形copy到另一个画布里面

public function yuan_img($imgUrl) {
		ini_set ( 'default_socket_timeout', 1 );
		$wh = getimagesize ( $imgUrl );
		$w = $wh [0];
		$h = $wh [1];
		$src_img = imagecreatefromstring ( file_get_contents ( $imgUrl ) );
		$img = imagecreatetruecolor ( $w, $h );
		imagesavealpha ( $img, true );
		//拾取一个完全透明的颜色,最后一个参数127为全透明
		$bg = imagecolorallocatealpha ( $img, 255, 255, 255, 127 );
		imagefill ( $img, 0, 0, $bg );
		$w2 = min ( $w, $h );
		$h2 = $w;
		$r = $w2 / 2; //圆半径
		if ($w < $h) { //宽大于高
			$y_x = $r; //圆心X坐标
			$y_y = $h / 2; //圆心Y坐标
		} else { //宽小于高
			$y_x = $w / 2; //圆心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 - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) < ($r * $r))) {
					imagesetpixel ( $img, $x, $y, $rgbColor ); //在指定的坐标绘制像素
				}
			}
		}
		//1.创建画布
		$im = imagecreatetruecolor ( $w2, $h2 );
		//2.上色
		$color = imagecolorallocate ( $im, 255, 255, 255 );
		//3.设置透明
		imagecolortransparent ( $im, $color );
		imagefill ( $im, 0, 0, $color );
		if ($w < $h) { //宽大于高
			imagecopy ( $im, $img, 0, 0, 0, ($h / 2) - $r, $w2, $h2 );
		} else { //宽小于高
			imagecopy ( $im, $img, 0, 0, ($w / 2) - $r, 0, $w2, $h2 );
		}
		//浏览器输出圆形图
		header ( "content-type:image/png" );
		imagepng ( $im);
	}
	
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值