php 创建png8格式的图片 与png、jpg格式互转

php 创建png8格式的图片 代码如下

<?php
// Create a new true color image
$im = new imagecreatetruecolor(100, 100);;

// Fill with alpha background
$alphabg = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $alphabg);

// Convert to palette-based with no dithering and 255 colors with alpha
imagetruecolortopalette($im, false, 255);
imagesavealpha($im, true);

// Save the image
imagepng($im, './paletteimage.png');
imagedestroy($im);
?>

php实现jpg图片与png图片互相转换函数:

/**
 *转换格式
 *
 */
function change_type($filepath,$filename,$type = 'png') {
	//获取图片的宽高等信息
	$img = $filepath.$filename;
	$info = GetImageSize($img);
	$width = $info[0];
	$height = $info[1];
	$temp = explode(".",$filename); 
	$new_filename = $temp[0] .'.' . $type;
	$save_path = $filepath . $new_filename;
	switch ($type) {
		case 'png' :
			$im = imagecreatefromjpeg($img);
			// Fill with alpha background
			$alphabg = imagecolorallocatealpha($im, 0, 0, 0, 127);
			imagefill($im, 0, 0, $alphabg);
			
			// Convert to palette-based with no dithering and 255 colors with alpha
			imagetruecolortopalette($im, false, 255);
			imagesavealpha($im, true);
			// Save the image
			imagepng($im, $save_path);
			imagedestroy($im);
			$process = true;
			break;
			
		case 'jpeg' :
		default :
			$image = imagecreatefrompng($img);
			imagejpeg($image, $save_path, 60);;
			imagedestroy($image);
			$process = true;
			break;
	}
	$filesize = filesize($save_path);
	$json_all=array();
	$json=array(
		"filename"=>$new_filename,
		"width"=>$width,
		"size"=>$this->formatSizeUnits($filesize)
	);
	array_push($json_all,$json);


	return $json_all;

}