PHP图片压缩,再转base64传输

<?php
/**
 * 获取图片的Base64编码(不支持url)
 * @param $img_file
 * @return string
 */
function img_to_base64($img_file) {

    $img_base64 = '';
    if (file_exists($img_file)) {
        $app_img_file = $img_file; // 图片路径
        $img_info = getimagesize($app_img_file); // 取得图片的大小,类型等

        //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
        $fp = fopen($app_img_file, "r"); // 图片是否可读权限

        if ($fp) {
            $filesize = filesize($app_img_file);
            $content = fread($fp, $filesize);
            $file_content = base64_encode($content); // base64编码
            switch ($img_info[2]) {           //判读图片类型
                case 1: $img_type = "gif";
                    break;
                case 2: $img_type = "jpg";
                    break;
                case 3: $img_type = "png";
                    break;
            }

            $img_base64 = $file_content;//合成图片的base64编码
//            file_put_contents('/usr/local/paperless/apache/11.txt',$img_base64. PHP_EOL, FILE_APPEND);

        }
        fclose($fp);
    }

    return $img_base64; //返回图片的base64
}

/**
 * 压缩图片大小
 * @param $img_file
 * @param int $percent
 * @param int $quality
 * @param int $new_width    指定的宽度
 * @param int $new_height   指定的高度
 */
function imgcompress($img_file,$percent=1,$quality=100,$new_width=0,$new_height=0){
    list($width, $height, $type, $attr) = getimagesize($img_file);
    $type = image_type_to_extension($type,false);
    $fun = "imagecreatefrom".$type;
    $image = $fun($img_file);

    if ($new_height==0 && $new_width==0){
        //如果没有指定宽高,则按比例计算
        $new_width = $width * $percent;
        $new_height = $height * $percent;
    }

    $image_thump = imagecreatetruecolor($new_width,$new_height);
    //将原图复制带图片载体上面,并且按照一定比例压缩,极大的保持了清晰度
    imagecopyresampled($image_thump,$image,0,0,0,0,$new_width,$new_height,$width,$height);
    imagedestroy($image);
//    unlink($img_file);
    $image = $image_thump;

    $funcs = "image".$type;
    if ($type == 'jpeg'){
        $funcs($image,$img_file,$quality);
    }else{
        $funcs($image,$img_file);
    }

}

imgcompress($outpath,1,70,1024,600);
//图片转base64存储
$img_base64 = img_to_base64($outpath);
unlink($outpath);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值