Он часто используется для сжатия больших загруженных изображений, особенно объема. Приложения, такие как Wechat, также по умолчанию сжимаются. Итак, как существенно сжать изображения, но при этом сохранить высокую четкость?
Сжатие обычно масштабируется, и задается сжатие по ширине, эффект очень хороший, цифровая камера сделала 4 м снимков, сжатых для поддержания высокой четкости и высокого значения исходной ширины, всего 700 тыс.
Вот код (есть два файла, img сжимается. класс. Класс PHP и сжатие. php )
Вот код (есть два файла, img сжимается. класс. Класс PHP и сжатие. php )
compressImg($dst_img);
Вот код (есть два файла, img сжимается. класс. Класс PHP и сжатие. php )
src = $src;
$this->percent = $percent;
}
/ ** High Definition Compressed Pictures
*@ Param string $saveName provides the image name (without extension, with source map extension) for saving. Or do not provide direct display of filename
*/
public function compressImg($saveName='')
{
$this->_openImage();
If (! Empty ($saveName), $this - >_saveImage ($saveName); // Save
else $this->_showImage();
}
/**
* Inside: Open the picture
*/
private function _openImage()
{
list($width, $height, $type, $attr) = getimagesize($this->src);
$this->imageinfo = array(
'width'=>$width,
'height'=>$height,
'type'=>image_type_to_extension($type,false),
'attr'=>$attr
);
$fun = "imagecreatefrom".$this->imageinfo['type'];
$this->image = $fun($this->src);
$this->_thumpImage();
}
/**
* Internal: Operating pictures
*/
private function _thumpImage()
{
$new_width = $this->imageinfo['width'] * $this->percent;
$new_height = $this->imageinfo['height'] * $this->percent;
$image_thump = imagecreatetruecolor($new_width,$new_height);
// The original image is duplicated on the image carrier, and compressed in a certain proportion, which greatly maintains the clarity.
imagecopyresampled($image_thump,$this->image,,,,,$new_width,$new_height,$this->imageinfo['width'],$this->imageinfo['height']);
imagedestroy($this->image);
$this->image = $image_thump;
}
/**
* Output picture: save image ()
*/
private function _showImage()
{
header('Content-Type: image/'.$this->imageinfo['type']);
$funcs = "image".$this->imageinfo['type'];
$funcs($this->image);
}
/**
* Save the picture to the hard disk:
*@ Param string $dstImgName, specifiable string name without suffix, using source graph extension. Directly specify the target image name with an extension.
*/
private function _saveImage($dstImgName)
{
if(empty($dstImgName)) return false;
AllowImgs = ['.jpg','.jpeg','.png','.bmp','.wbmp','.gif']; //If the target image name has a suffix, suffix it with the target image extension; if not, use the source image extension.
$dstExt = strrchr($dstImgName ,".");
$sourseExt = strrchr($this->src ,".");
if(!empty($dstExt)) $dstExt =strtolower($dstExt);
if(!empty($sourseExt)) $sourseExt =strtolower($sourseExt);
// Has a specified target name extension
if(!empty($dstExt) && in_array($dstExt,$allowImgs)){
$dstName = $dstImgName;
}elseif(!empty($sourseExt) && in_array($sourseExt,$allowImgs)){
$dstName = $dstImgName.$sourseExt;
}else{
$dstName = $dstImgName.$this->imageinfo['type'];
}
$funcs = "image".$this->imageinfo['type'];
$funcs($this->image,$dstName);
}
/**
* Destroy pictures
*/
public function __destruct(){
imagedestroy($this->image);
}
}После использования личное ощущение в процентах составляет около 0,5 доллара. Качество сжатого изображения в основном такое же, как и у исходного изображения.
резюме
Выше приведен код реализации функции сжатия изображений высокой четкости PHP без потерь, введенной Xiaobian. Я надеюсь, что это будет полезно для вас. Если у вас есть какие-либо вопросы, пожалуйста, оставьте мне сообщение, Сяобянь ответит вам вовремя. Большое вам спасибо за вашу поддержку в развитии peer.