1. 程式人生 > >PHP 壓縮圖片質量

PHP 壓縮圖片質量

$imageFileName = './test2.jpg';
$uploadfile_resize = $imageFileName;
$pic_width_max = 1000;
$pic_height_max = 1000;
$file_type = getimagesize($imageFileName)['mime'];

if($file_type == "image/pjpeg"||$file_type == "image/jpg"|$file_type == "image/jpeg"){
$im = imagecreatefromjpeg($imageFileName);
}else if($file_type == "image/x-png"){
$im = imagecreatefromjpeg($imageFileName);
}else if($file_type == "image/gif"){
$im = imagecreatefromjpeg($imageFileName);
}else {//預設jpg
$im = imagecreatefromjpeg($imageFileName);
}
if($im) {
ResizeImage($im, $pic_width_max, $pic_height_max, $uploadfile_resize);
ImageDestroy($im);
}



function resizeImage($uploadfile,$maxwidth,$maxheight,$filename){
//取得當前圖片大小
$width = imagesx($uploadfile);
$height = imagesy($uploadfile);

//壓縮比值
$i=0.5;
//生成縮圖的大小
if(($width > $maxwidth) || ($height > $maxheight)){
$newwidth = $width * $i;
$newheight = $height * $i;
if(function_exists("imagecopyresampled")){
$uploaddir_resize = imagecreatetruecolor($newwidth, $newheight);
//echo $uploaddir_resize;
imagecopyresampled($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
}else{
$uploaddir_resize = imagecreate($newwidth, $newheight);
imagecopyresized($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
}

ImageJpeg ($uploaddir_resize,$filename);
ImageDestroy ($uploaddir_resize);
}else{
ImageJpeg ($uploadfile,$filename);
}
}