Home > Article > Backend Development > How to create compressed images in PHP
This article mainly introduces the method of creating compressed images in PHP. The function of compressing images is implemented through custom functions. It involves skills related to reading PHP images and creating graphic images. Friends in need can refer to the following
The details are as follows:
<?php //创建压缩图 function _create_thumbnail($srcFile, $toW, $toH, $toFile="") { if ($toFile == "") { $toFile = $srcFile; } $info = ""; $data = getimagesize($srcFile, $info); if (!$data) return false; //将文件载入到资源变量im中 switch ($data[2]) { case 1: $im = imagecreatefromgif($srcFile); break; case 2: $im = imagecreatefromjpeg($srcFile); break; case 3: $im = imagecreatefrompng($srcFile); break; } //计算缩略图的宽高 $srcW = imagesx($im); $srcH = imagesy($im); $toWH = $toW / $toH; $srcWH = $srcW / $srcH; if ($toWH <= $srcWH) { $ftoW = $toW; $ftoH = (int)($ftoW * ($srcH / $srcW)); } else { $ftoH = $toH; $ftoW = (int)($ftoH * ($srcW / $srcH)); } if (function_exists("imagecreatetruecolor")) { $ni = imagecreatetruecolor($ftoW, $ftoH); //新建一个真彩色图像 if ($ni) { //重采样拷贝部分图像并调整大小 可保持较好的清晰度 imagecopyresampled($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); } else { //拷贝部分图像并调整大小 $ni = imagecreate($ftoW, $ftoH); imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); } } else { $ni = imagecreate($ftoW, $ftoH); imagecopyresized($ni, $im, 0, 0, 0, 0, $ftoW, $ftoH, $srcW, $srcH); } //保存到文件 统一为.png格式 imagepng($ni, $toFile); //以 PNG 格式将图像输出到浏览器或文件 ImageDestroy($ni); ImageDestroy($im); } ?>
phpDetailed explanation of WeChat public platform interaction and interface
## php Detailed explanation of file upload
WeChat public account js-sdk development application
The above is the detailed content of How to create compressed images in PHP. For more information, please follow other related articles on the PHP Chinese website!