【php】常用方法

图片等比压缩

ImgCompress.php

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

    private $src;
    private $image;
    private $imageinfo;
    private $percent = 0.5;

    /**
     * 图片压缩
     * @param $src 源图
     * @param float $percent 压缩比例
     */
    public function __construct($src, $percent = 1)
    {
        $this->src = $src;
        $this->percent = $percent;
    }


    /** 高清压缩图片
     * @param string $saveName 提供图片名(可不带扩展名,用源图扩展名)用于保存。或不提供文件名直接显示
     */
    public function compressImg($saveName = '')
    {
        $this->_openImage();
        if (!empty($saveName)) $this->_saveImage($saveName);  //保存
        else $this->_showImage();
    }

    /**
     * 内部:打开图片
     */
    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();
    }

    /**
     * 内部:操作图片
     */
    private function _thumpImage()
    {
        $new_width = $this->imageinfo['width'] * $this->percent;
        $new_height = $this->imageinfo['height'] * $this->percent;
        $image_thump = imagecreatetruecolor($new_width, $new_height);
        //将原图复制带图片载体上面,并且按照一定比例压缩,极大的保持了清晰度
       
        imagealphablending($image_thump,false);//这里很重要,意思是不合并颜色,直接用$img图像颜色替换,包括透明色;
        imagesavealpha($image_thump,true);//

        
        imagecopyresampled($image_thump, $this->image, 0, 0, 0, 0, $new_width, $new_height, $this->imageinfo['width'], $this->imageinfo['height']);
        imagedestroy($this->image);
        $this->image = $image_thump;
    }

    /**
     * 输出图片:保存图片则用saveImage()
     */
    private function _showImage()
    {
        header('Content-Type: image/' . $this->imageinfo['type']);
        $funcs = "image" . $this->imageinfo['type'];
        $funcs($this->image);
    }

    /**
     * 保存图片到硬盘:
     * @param string $dstImgName 1、可指定字符串不带后缀的名称,使用源图扩展名 。2、直接指定目标图片名带扩展名。
     */
    private function _saveImage($dstImgName)
    {
        if (empty($dstImgName)) return false;
        //如果目标图片名有后缀就用目标图片扩展名 后缀,如果没有,则用源图的扩展名
        $allowImgs = ['.jpg', '.jpeg', '.png', '.bmp', '.wbmp', '.gif'];   
        $dstExt = strrchr($dstImgName, ".");
        $sourseExt = strrchr($this->src, ".");
        if (!empty($dstExt)) $dstExt = strtolower($dstExt);
        if (!empty($sourseExt)) $sourseExt = strtolower($sourseExt);

        //有指定目标名扩展名
        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);
    }

    /**
     * 销毁图片
     */
    public function __destruct()
    {
        imagedestroy($this->image);
    }

}

调用方式:

  require './ImgCompress.php';
  $img = new ImgCompress($bigImgSrc, $percent);
  $img->compressImg($dstImgSrc);

压缩图至传入的最大值

方法一:压缩后保存文件到传入的路径

/**
 * 图片压缩,并保存为原始图片类型。
 *
 * @param string $srcImagePath 原始图片路径。
 * @param string $outImagePath 输出图片路径。
 * @param int $maxSize 最大压缩尺寸。
 */
function compressImage($srcImagePath, $outImagePath, $maxSize = 800)
{
    list($srcWidth, $srcHeight, $srcType) = getimagesize($srcImagePath);

    // 检查是否需要修改图片大小
    if ($srcWidth > $maxSize || $srcHeight > $maxSize) {
        // 计算压缩后的宽度和高度
        $ratio = min($maxSize / $srcWidth, $maxSize / $srcHeight);
        $outWidth = $srcWidth * $ratio;
        $outHeight = $srcHeight * $ratio;

        // 创建新的图像资源
        $outImage = imagecreatetruecolor($outWidth, $outHeight);

        // 处理PNG图片的透明度
        if ($srcType == IMAGETYPE_PNG) {
            imagealphablending($outImage, false);
            imagesavealpha($outImage, true);
            $transparent = imagecolorallocatealpha($outImage, 0, 0, 0, 127);
            imagefilledrectangle($outImage, 0, 0, $outWidth, $outHeight, $transparent);
        }

        // 加载原始图片并缩放到输出大小
        $srcImage = imagecreatefromstring(file_get_contents($srcImagePath));
        imagecopyresampled($outImage, $srcImage, 0, 0, 0, 0, $outWidth, $outHeight, $srcWidth, $srcHeight);

        // 输出图像资源到文件,保持原始图片类型
        switch ($srcType) {
            case IMAGETYPE_JPEG:
                imagejpeg($outImage, $outImagePath);
                break;
            case IMAGETYPE_PNG:
                imagepng($outImage, $outImagePath);
                break;
            default:
                die('Unsupported image type.');
        }

        // 释放图像资源
        imagedestroy($srcImage);
        imagedestroy($outImage);
    } else {
        // 如果宽度和高度都小于等于800,则直接复制原始图片到输出文件
        copy($srcImagePath, $outImagePath);
    }
}

方法二:压缩包返回图片内容

function compressImage($srcImagePath, $srcImageContent, $maxSize = 800)
{
    list($srcWidth, $srcHeight, $srcType) = getimagesize($srcImagePath);

    // 检查是否需要修改图片大小
    if ($srcWidth > $maxSize || $srcHeight > $maxSize) {
        // 计算压缩后的宽度和高度
        $ratio = min($maxSize / $srcWidth, $maxSize / $srcHeight);
        $outWidth = $srcWidth * $ratio;
        $outHeight = $srcHeight * $ratio;

        // 创建新的图像资源
        $outImage = imagecreatetruecolor($outWidth, $outHeight);

        // 处理PNG图片的透明度
        if ($srcType == IMAGETYPE_PNG) {
            imagealphablending($outImage, false);
            imagesavealpha($outImage, true);
            $transparent = imagecolorallocatealpha($outImage, 0, 0, 0, 127);
            imagefilledrectangle($outImage, 0, 0, $outWidth, $outHeight, $transparent);
        }

        // 加载原始图片并缩放到输出大小
        $srcImage = imagecreatefromstring($srcImageContent);
        imagecopyresampled($outImage, $srcImage, 0, 0, 0, 0, $outWidth, $outHeight, $srcWidth, $srcHeight);

        // 将图像资源转换为对应的图像内容并返回
        ob_start();
        switch ($srcType) {
            case IMAGETYPE_JPEG:
                imagejpeg($outImage);
                break;
            case IMAGETYPE_PNG:
                imagepng($outImage);
                break;
            default:
                die('Unsupported image type.');
        }
        $imageContent = ob_get_clean();

        // 释放图像资源
        imagedestroy($srcImage);
        imagedestroy($outImage);

        return $imageContent;
    } else {
        // 如果宽度和高度都小于等于800,则直接返回原始图片内容
        return $srcImageContent;
    }
}

图片转base64

// 不带前缀
function base64EncodeImage($image_file)
{
    $base64_image = '';
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image =  chunk_split(base64_encode($image_data));
    return $base64_image;
}
// 带前缀
function base64EncodeImage2($image_file)
{
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}
// 图片url转base64
function imgurltobase64($img)
{
    $type = getimagesize($img); //取得图片的大小,类型等
    $content = file_get_contents($img);
    //已经将图片转成base64编码
    $file_content = base64_encode($content);

    switch ($type[2]) { //判读图片类型
        case 1:
            $img_type = "gif";
            break;
        case 2:
            $img_type = "jpg";
            break;
        case 3:
            $img_type = "png";
            break;
    }
    //合成图片的base64编码,方便在页面中展示
    return 'data:image/' . $img_type . ';base64,' . $file_content;
}

写内容到文本中

/**
 * 记录信息到txt文件中
 *
 * @param $txt:txt文件的路径,$content:要写入的内容,$mode:操作
 */
function saveSthToTxt($txt, $content, $mode){
    $myfile = fopen($txt, $mode);
    fwrite($myfile, $content);
    fclose($myfile);
}

zip解压方法

/**
 * zip解压方法
 * @param string $filePath 压缩包所在地址 【绝对文件地址】d:/test/123.zip
 * @param string $path 解压路径 【绝对文件目录路径】d:/test
 * @return bool
 */
function unzip($filePath, $path) {
    if (empty($path) || empty($filePath)) {
        return false;
    }

    $zip = new ZipArchive();

    if ($zip->open($filePath) === true) {
        $zip->extractTo($path);
        $zip->close();
        return true;
    } else {
        return false;
    }
}

http状态码

/** 
* HTTP Protocol defined status codes
* HTTP协议状态码,调用函数时候只需要将$num赋予一个下表中的已知值就直接会返回状态了。
* @param int $num
*/ 
function https($num) { 
    $http = array ( 
        100 => "HTTP/1.1 100 Continue", 
        101 => "HTTP/1.1 101 Switching Protocols", 
        200 => "HTTP/1.1 200 OK", 
        201 => "HTTP/1.1 201 Created", 
        202 => "HTTP/1.1 202 Accepted", 
        203 => "HTTP/1.1 203 Non-Authoritative Information", 
        204 => "HTTP/1.1 204 No Content", 
        205 => "HTTP/1.1 205 Reset Content", 
        206 => "HTTP/1.1 206 Partial Content", 
        300 => "HTTP/1.1 300 Multiple Choices", 
        301 => "HTTP/1.1 301 Moved Permanently", 
        302 => "HTTP/1.1 302 Found", 
        303 => "HTTP/1.1 303 See Other", 
        304 => "HTTP/1.1 304 Not Modified", 
        305 => "HTTP/1.1 305 Use Proxy", 
        307 => "HTTP/1.1 307 Temporary Redirect", 
        400 => "HTTP/1.1 400 Bad Request", 
        401 => "HTTP/1.1 401 Unauthorized", 
        402 => "HTTP/1.1 402 Payment Required", 
        403 => "HTTP/1.1 403 Forbidden", 
        404 => "HTTP/1.1 404 Not Found", 
        405 => "HTTP/1.1 405 Method Not Allowed", 
        406 => "HTTP/1.1 406 Not Acceptable", 
        407 => "HTTP/1.1 407 Proxy Authentication Required", 
        408 => "HTTP/1.1 408 Request Time-out", 
        409 => "HTTP/1.1 409 Conflict", 
        410 => "HTTP/1.1 410 Gone", 
        411 => "HTTP/1.1 411 Length Required", 
        412 => "HTTP/1.1 412 Precondition Failed", 
        413 => "HTTP/1.1 413 Request Entity Too Large", 
        414 => "HTTP/1.1 414 Request-URI Too Large", 
        415 => "HTTP/1.1 415 Unsupported Media Type", 
        416 => "HTTP/1.1 416 Requested range not satisfiable", 
        417 => "HTTP/1.1 417 Expectation Failed", 
        500 => "HTTP/1.1 500 Internal Server Error", 
        501 => "HTTP/1.1 501 Not Implemented", 
        502 => "HTTP/1.1 502 Bad Gateway", 
        503 => "HTTP/1.1 503 Service Unavailable", 
        504 => "HTTP/1.1 504 Gateway Time-out"  
    ); 
    header($http[$num]); 
} 

未完待续。。。会持续更新

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值