王新阳

wangxinyang

php判断png/gif/webp是否背景透明

function isPngTransparent($filePath) {
	$image = imagecreatefrompng($filePath);
	if (!$image) return false;
	
	// 获取图像尺寸
	$width = imagesx($image);
	$height = imagesy($image);
	
	// 检查alpha通道
	if (imagecolortransparent($image) >= 0) {
		return true;
	}
	
	// 逐像素检查透明度
	for ($x = 0; $x < $width; $x++) {
		for ($y = 0; $y < $height; $y++) {
			$color = imagecolorat($image, $x, $y);
			$alpha = ($color >> 24) & 0xFF;
			if ($alpha > 0) {
				//imagedestroy($image);
				return true;
			}
		}
	}
	
	imagedestroy($image);
	return false;
}
function isGifTransparent($filePath) {
	$image = imagecreatefromgif($filePath);
	if (!$image) return false;
	
	// 获取透明色索引
	$transparentIndex = imagecolortransparent($image);
	
	// 如果有透明色索引
	if ($transparentIndex >= 0) {
		// 获取调色板中的透明色
		$transparentColor = imagecolorsforindex($image, $transparentIndex);
		if ($transparentColor['alpha'] == 127) {
			//imagedestroy($image);
			return true;
		}
	}
	
	imagedestroy($image);
	return false;
}
function isWebpTransparent($filePath) {
	if (!function_exists('imagecreatefromwebp')) {
		throw new Exception('WebP支持未启用');
	}
	
	$image = imagecreatefromwebp($filePath);
	if (!$image) return false;
	
	$width = imagesx($image);
	$height = imagesy($image);
	
	// WebP支持alpha通道,检查方式类似PNG
	for ($x = 0; $x < $width; $x++) {
		for ($y = 0; $y < $height; $y++) {
			$color = imagecolorat($image, $x, $y);
			$alpha = ($color >> 24) & 0xFF;
			if ($alpha > 0) {
				//imagedestroy($image);
				return true;
			}
		}
	}
	
	imagedestroy($image);
	return false;
}
2026-01-14
2026-01-17 星期六 农历冬月二十九