php图片压缩指定大小指定体积kb代码

代码语言:php

所属分类:图片处理

代码描述:php图片压缩指定大小指定体积kb代码

代码标签: 指定 大小 指定 体积 kb

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<?php
/**
* 图片压缩类:通过缩放来压缩。
* 如果要保持源图比例,把参数$percent保持为1即可。
* 即使原比例压缩,也可大幅度缩小。数码相机4M图片。也可以缩为700KB左右。如果缩小比例,则体积会更小。
* 结果:可保存、可直接显示。
*/

class imgcompress
{
   
private $image;
   
private $imageinfo;

   
/**
    * [compressImg 图片压缩操作]
    * @param  [type]  $url      [图片路径]
    * @param  integer $percent  [缩放比例(或缩放后尺寸)]
    * @param  string  $saveName [保存文件名称(可不带扩展名,用源图扩展名)]
    * @return [type]            [description]
    */

   
public function compressImg($url, $percent = 1, $saveName = '') {
        $re
= $this->_openImage($url);
       
if ($this->imageinfo) {
            $this
->_thumpImage($percent);
           
if (!empty($saveName)) {
                $this
->_saveImage($url, $saveName); //保存
           
} else {
                $url
!= $saveName && $this->_showImage();
           
}
           
return true;
       
} else {
           
return false;
       
}
   
}

   
/**
    * 内部:打开图片
    */

   
private function _openImage($url) {
        $image
= @file_get_contents($url); // 将 logo 读取到字符串中
       
if (!$image)
           
return false;

        $imagedetail
= getimagesizefromstring($image);
        list
($width, $height, $type, $attr) = $imagedetail;
       
if (!$width)
           
return false;

        $this
->imageinfo = array(
           
'width' => $width,
           
'height' => $height,
           
'type' => image_type_to_extension($type, false),
           
'attr' => $attr
       
);
        $this
->image = imagecreatefromstring($image); // 从字符串中的图像流新建一图像
   
}

   
/**
    * 内部:操作图片
    */

   
private function _thumpImage($percent) {
       
if ($percent > 1 && $percent < $this->imageinfo['height'] && $percent < $this->imageinfo['width']) {
           
if ($this->imageinfo['height'] < $this->imageinfo['width']) {
                $percent
= $percent / $this->imageinfo['height'];
           
} else {
                $percent
= $percent / $this->imageinfo['width'];
           
}
       
}
        $ratio
= $percent > 1 ? 1 : $percent;
        $new_width
= $this->imageinfo['width'] * $ratio;
        $new_height
= $this->imageinfo['.........完整代码请登录后点击上方下载按钮下载查看

网友评论0