图片上传自动压缩php,上传图片压缩怎么弄

本文目录一览:

PHP、HTML5上传图片自动压缩问题

给你个图片处理的类吧,图片剪裁处理后,也就等于将图片压缩了。

/**

* 图像处理类

* ============================================================================

 * Copyright 2014 大秦科技,并保留所有权利。

 * 网站地址: ;

 * ============================================================================

*/

class Image{

    //生成缩略图的方式

    public $thumbType;

    //缩略图的宽度

    public $thumbWidth;

    //缩略图的高度

    public $thumbHeight;

    //生成缩略图文件名后缀

    public $thumbEndFix;

    //缩略图文件前缀

    public $thumbPreFix;

    /**

     * 构造函数

     */

    public function __construct(){

        $this-thumbType = 1;

        $this-thumbWidth = 120;

        $this-thumbHeight = 60;

        $this-thumbPreFix =”;

        $this-thumbEndFix =  ‘_thumb’;

    }

    /**

     * 检测是否为图像文件

     * @param $img 图像

     * @return bool

     */

    private function check($img){

        $type = array(“.jpg”, “.jpeg”, “.png”, “.gif”);

        $imgType = strtolower(strrchr($img, ‘.’));

        return extension_loaded(‘gd’)  file_exists($img)  in_array($imgType, $type);

    }

    /**

     * 获得缩略图的尺寸信息

     * @param $imgWidth 原图宽度

     * @param $imgHeight 原图高度

     * @param $thumbWidth 缩略图宽度

     * @param $thumbHeight 缩略图的高度

     * @param $thumbType 处理方式

     * 1 固定宽度  高度自增 2固定高度  宽度自增 3固定宽度  高度裁切

     * 4 固定高度 宽度裁切 5缩放最大边 原图不裁切

     * @return mixed

     */

    private function thumbSize($imgWidth, $imgHeight, $thumbWidth, $thumbHeight, $thumbType){

        //初始化缩略图尺寸

        $w = $thumbWidth;

        $h = $thumbHeight;

        //初始化原图尺寸

        $cuthumbWidth = $imgWidth;

        $cuthumbHeight = $imgHeight;

        switch ($thumbType) {

            case 1 :

                //固定宽度  高度自增

                $h = $thumbWidth / $imgWidth * $imgHeight;

                break;

            case 2 :

                //固定高度  宽度自增

                $w = $thumbHeight / $imgHeight * $imgWidth;

                break;

            case 3 :

                //固定宽度  高度裁切

                $cuthumbHeight = $imgWidth / $thumbWidth * $thumbHeight;

                break;

            case 4 :

                //固定高度  宽度裁切

                $cuthumbWidth = $imgHeight / $thumbHeight * $thumbWidth;

                break;

            case 5 :

                //缩放最大边 原图不裁切

                if (($imgWidth / $thumbWidth)  ($imgHeight / $thumbHeight)) {

                    $h = $thumbWidth / $imgWidth * $imgHeight;

                } elseif (($imgWidth / $thumbWidth)  ($imgHeight / $thumbHeight)) {

                    $w = $thumbHeight / $imgHeight * $imgWidth;

                } else {

                    $w = $thumbWidth;

                    $h = $thumbHeight;

                }

                break;

            default:

                //缩略图尺寸不变,自动裁切图片

                if (($imgHeight / $thumbHeight)  ($imgWidth / $thumbWidth)) {

                    $cuthumbWidth = $imgHeight / $thumbHeight * $thumbWidth;

                } elseif (($imgHeight / $thumbHeight)  ($imgWidth / $thumbWidth)) {

                    $cuthumbHeight = $imgWidth / $thumbWidth * $thumbHeight;

                }

//            }

        }

        $arr [0] = $w;

        $arr [1] = $h;

        $arr [2] = $cuthumbWidth;

        $arr [3] = $cuthumbHeight;

        return $arr;

    }

    /**

     * 图片裁切处理

     * @param $img 原图

     * @param string $outFile 另存文件名

     * @param string $thumbWidth 缩略图宽度

     * @param string $thumbHeight 缩略图高度

     * @param string $thumbType 裁切图片的方式

     * 1 固定宽度  高度自增 2固定高度  宽度自增 3固定宽度  高度裁切

     * 4 固定高度 宽度裁切 5缩放最大边 原图不裁切 6缩略图尺寸不变,自动裁切最大边

     * @return bool|string

     */

    public function thumb($img, $outFile = ”, $thumbWidth = ”, $thumbHeight = ”, $thumbType = ”){

        if (!$this-check($img)) {

            return false;

        }

        //基础配置

        $thumbType = $thumbType ? $thumbType : $this-thumbType;

        $thumbWidth = $thumbWidth ? $thumbWidth : $this-thumbWidth;

        $thumbHeight = $thumbHeight ? $thumbHeight : $this-thumbHeight;

        //获得图像信息

        $imgInfo = getimagesize($img);

        $imgWidth = $imgInfo [0];

        $imgHeight = $imgInfo [1];

        $imgType = image_type_to_extension($imgInfo [2]);

        //获得相关尺寸

        $thumb_size = $this-thumbSize($imgWidth, $imgHeight, $thumbWidth, $thumbHeight, $thumbType);

        //原始图像资源

        $func = “imagecreatefrom” . substr($imgType, 1);

        $resImg = $func($img);

        //缩略图的资源

        if ($imgType == ‘.gif’) {

            $res_thumb = imagecreate($thumb_size [0], $thumb_size [1]);

            $color = imagecolorallocate($res_thumb, 255, 0, 0);

        } else {

            $res_thumb = imagecreatetruecolor($thumb_size [0], $thumb_size [1]);

            imagealphablending($res_thumb, false); //关闭混色

            imagesavealpha($res_thumb, true); //储存透明通道

        }

        //绘制缩略图X

        if (function_exists(“imagecopyresampled”)) {

            imagecopyresampled($res_thumb, $resImg, 0, 0, 0, 0, $thumb_size [0], $thumb_size [1], $thumb_size [2], $thumb_size [3]);

        } else {

            imagecopyresized($res_thumb, $resImg, 0, 0, 0, 0, $thumb_size [0], $thumb_size [1], $thumb_size [2], $thumb_size [3]);

        }

        //处理透明色

        if ($imgType == ‘.gif’) {

            imagecolortransparent($res_thumb, $color);

        }

        //配置输出文件名

        $imgInfo = pathinfo($img);

        $outFile = $outFile ? $outFile :dirname($img).’/’. $this-thumbPreFix . $imgInfo[‘filename’] . $this-thumbEndFix . “.” . $imgInfo[‘extension’];

        Files::create(dirname($outFile));

        $func = “image” . substr($imgType, 1);

        $func($res_thumb, $outFile);

        if (isset($resImg))

            imagedestroy($resImg);

        if (isset($res_thumb))

            imagedestroy($res_thumb);

        return $outFile;

    }

}

PHP网站上传图片自动压缩,怎么编程啊,求指

这里会使用到三个文件:

connect.php:连接数据库

test_upload.php:执行SQL语句

upload_img.php:上传图片并压缩

三个文件代码如下:

连接数据库:connect.php

?php

$db_host = ”;

$db_user = ”;

$db_psw = ”;

$db_name = ”;

$db_port = ”;

$sqlconn=new mysqli($db_host,$db_user,$db_psw,$db_name);

$q=”set names utf8;”;

$result=$sqlconn-query($q);

if (mysqli_connect_errno()) {

 printf(“Connect failed: %s\n”, mysqli_connect_error());

 exit();

}

?

当然使用一些封装的数据库类也是可以的。

执行SQL语句:test_upload.php

?php

require (“connect.php”);

require (“upload_img.php”);

$real_img=$uploadfile; 

$small_img=$uploadfile_resize;

$insert_sql = “insert into img (real_img,small_img) values (?,?)”;

$result = $sqlconn – prepare($insert_sql);

$result – bind_param(“ss”, $real_img,$small_img);

$result – execute();

?

上传图片并压缩:upload_img.php

?php 

//设置文件保存目录

$uploaddir = “upfiles/”; 

//设置允许上传文件的类型

$type=array(“jpg”,”gif”,”bmp”,”jpeg”,”png”); 

 

//获取文件后缀名函数 

function fileext($filename) 

 return substr(strrchr($filename, ‘.’), 1); 

 

//生成随机文件名函数 

function random($length) 

 $hash = ‘CR-‘; 

 $chars = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz’; 

 $max = strlen($chars) – 1; 

 mt_srand((double)microtime() * 1000000); 

 for($i = 0; $i  $length; $i++) 

 { 

  $hash .= $chars[mt_rand(0, $max)]; 

 } 

 return $hash; 

 

$a=strtolower(fileext($_FILES[‘filename’][‘name’])); 

 

//判断文件类型 

if(!in_array(strtolower(fileext($_FILES[‘filename’][‘name’])),$type)) 

 $text=implode(“,”,$type); 

 $ret_code=3;//文件类型错误

 $page_result=$text;

 $retArray = array(‘ret_code’ = $ret_code,’page_result’=$page_result);

 $retJson = json_encode($retArray);

 echo $retJson;

 return;

 

//生成目标文件的文件名 

else

 $filename=explode(“.”,$_FILES[‘filename’][‘name’]); 

 do

 { 

  $filename[0]=random(10); //设置随机数长度 

  $name=implode(“.”,$filename); 

  //$name1=$name.”.Mcncc”; 

  $uploadfile=$uploaddir.$name; 

 } 

 

 while(file_exists($uploadfile)); 

 

 if (move_uploaded_file($_FILES[‘filename’][‘tmp_name’],$uploadfile)) 

 { 

  if(is_uploaded_file($_FILES[‘filename’][‘tmp_name’])) 

  {

   $ret_code=1;//上传失败

  } 

 else

 {//上传成功

  $ret_code=0;

 } 

 } 

$retArray = array(‘ret_code’ = $ret_code);

$retJson = json_encode($retArray);

echo $retJson;

}

 

//压缩图片

 

$uploaddir_resize=”upfiles_resize/”;

$uploadfile_resize=$uploaddir_resize.$name;

 

//$pic_width_max=120;

//$pic_height_max=90;

//以上与下面段注释可以联合使用,可以使图片根据计算出来的比例压缩

 

$file_type=$_FILES[“filename”][‘type’];

 

function ResizeImage($uploadfile,$maxwidth,$maxheight,$name)

{

 //取得当前图片大小

 $width = imagesx($uploadfile);

 $height = imagesy($uploadfile);

 $i=0.5;

 //生成缩略图的大小

 if(($width  $maxwidth) || ($height  $maxheight))

 {

  /*

  $widthratio = $maxwidth/$width;

  $heightratio = $maxheight/$height;

   

  if($widthratio  $heightratio)

  {

   $ratio = $widthratio;

  }

  else

  {

    $ratio = $heightratio;

  }

   

  $newwidth = $width * $ratio;

  $newheight = $height * $ratio;

  */

  $newwidth = $width * $i;

  $newheight = $height * $i;

  if(function_exists(“imagecopyresampled”))

  {

   $uploaddir_resize = imagecreatetruecolor($newwidth, $newheight);

   imagecopyresampled($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

  }

  else

  {

   $uploaddir_resize = imagecreate($newwidth, $newheight);

   imagecopyresized($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

  }

   

  ImageJpeg ($uploaddir_resize,$name);

  ImageDestroy ($uploaddir_resize);

 }

 else

 {

  ImageJpeg ($uploadfile,$name);

 }

}

 

 

 

if($_FILES[“filename”][‘size’])

{

 if($file_type == “image/pjpeg”||$file_type == “image/jpg”|$file_type == “image/jpeg”)

 {

  //$im = imagecreatefromjpeg($_FILES[$upload_input_name][‘tmp_name’]);

  $im = imagecreatefromjpeg($uploadfile);

 }

 elseif($file_type == “image/x-png”)

 {

  //$im = imagecreatefrompng($_FILES[$upload_input_name][‘tmp_name’]);

  $im = imagecreatefromjpeg($uploadfile);

 }

 elseif($file_type == “image/gif”)

 {

  //$im = imagecreatefromgif($_FILES[$upload_input_name][‘tmp_name’]);

  $im = imagecreatefromjpeg($uploadfile);

 }

 else//默认jpg

 {

  $im = imagecreatefromjpeg($uploadfile);

 }

 if($im)

 {

  ResizeImage($im,$pic_width_max,$pic_height_max,$uploadfile_resize);

  

  ImageDestroy ($im);

 }

?

请按照现实情况更改connect.php,test_upload.php中对应的信息。

望采纳,谢谢。

如何利用php把上传的图片压缩

?php

// The file

$filename = ‘test.jpg’;

$percent = 0.5;

// Content type

header(‘Content-Type: image/jpeg’);

// Get new dimensions

list($width, $height) = getimagesize($filename);

$new_width = $width * $percent;

$new_height = $height * $percent;

// Resample

$image_p = imagecreatetruecolor($new_width, $new_height);

$image = imagecreatefromjpeg($filename);

imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Output

imagejpeg($image_p, null, 100);

?

php图片上传能用代码压缩图片文件的大小吗

图片的格式是多变的,但是压缩图片的方式不变,压缩软件压缩图片一致都是那样,我将操作步骤写下来了,楼主可以看看

1、安装相对应的辅助工具(迅捷图片压缩软件)运行工具;

2、打开工具,看到页面上的图片压缩选项,点击这个蓝色的按钮进入将要实行操作的页面。

3、在页面上点击选择文件按钮,或是选择文件夹按钮,都可以将存放图片文件的文件夹打开,然后对图片进行选择。

4、选择文件时我们按住多选键Ctrl,选择我们需要压缩的图片添加到页面中间的位置。

5、做到这一步了,下面我们可以对压缩图片的压缩选项做一个选择,可以转换图片的格式,转化为png或者是jpg,将图片压缩可以选择的压缩选项如下。

6、将所有的参数设置完成之后我们点击页面上的“开始压缩按钮就可以进行压缩了。

日常使用的压缩图片的办法是将图片压缩为压缩包,在使用是还要对其解压才能使用,这种压缩方法压缩图片不同点在于不会将图片文件压缩为压缩包,能将图片最大限度的缩小,图片的状态不会改变。

php上传图片压缩

html里加一个表单,然后提交到处理上传文件的upload.php

类似下面这样

from action=”upload.php” enctype=”multipart/from-data” method=”post”

input type=”file” name=”file3″/

/from

然后upload.php里先处理图片上传,最终保存一份原始图片文件在服务器上,接着就把文件路径什么的传到你的这个函数里处理图片就OK了

php图片上传后被压缩了,变得不清晰了,怎么解决

如果清晰的上传后,不清晰,,那就是设置的压缩质量问题,,,如果是不清晰上传了,这肯定不会清晰了。。。

找到上传的设置里可以找到图片压缩比例。。。。

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/185889.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-11-26 21:08
下一篇 2024-11-26 21:08

相关推荐

  • PHP和Python哪个好找工作?

    PHP和Python都是非常流行的编程语言,它们被广泛应用于不同领域的开发中。但是,在考虑择业方向的时候,很多人都会有一个问题:PHP和Python哪个好找工作?这篇文章将从多个方…

    编程 2025-04-29
  • PHP怎么接币

    想要在自己的网站或应用中接受比特币等加密货币的支付,就需要对该加密货币拥有一定的了解,并使用对应的API进行开发。本文将从多个方面详细阐述如何使用PHP接受加密货币的支付。 一、环…

    编程 2025-04-29
  • 使用PHP foreach遍历有相同属性的值

    本篇文章将介绍如何使用PHP foreach遍历具有相同属性的值,并给出相应的代码示例。 一、基础概念 在讲解如何使用PHP foreach遍历有相同属性的值之前,我们需要先了解几…

    编程 2025-04-28
  • PHP获取301跳转后的地址

    本文将为大家介绍如何使用PHP获取301跳转后的地址。301重定向是什么呢?当我们访问一个网页A,但是它已经被迁移到了另一个地址B,此时若服务器端做了301重定向,那么你的浏览器在…

    编程 2025-04-27
  • PHP登录页面代码实现

    本文将从多个方面详细阐述如何使用PHP编写一个简单的登录页面。 1. PHP登录页面基本架构 在PHP登录页面中,需要包含HTML表单,用户在表单中输入账号密码等信息,提交表单后服…

    编程 2025-04-27
  • PHP与Python的比较

    本文将会对PHP与Python进行比较和对比分析,包括语法特性、优缺点等方面。帮助读者更好地理解和使用这两种语言。 一、语法特性 PHP语法特性: <?php // 简单的P…

    编程 2025-04-27
  • PHP版本管理工具phpenv详解

    在PHP项目开发过程中,我们可能需要用到不同版本的PHP环境来试验不同的功能或避免不同版本的兼容性问题。或者我们需要在同一台服务器上同时运行多个不同版本的PHP语言。但是每次手动安…

    编程 2025-04-24
  • PHP数组去重详解

    一、array_unique函数 array_unique是php中常用的数组去重函数,它基于值来判断元素是否重复,具体使用方法如下: $array = array(‘a’, ‘b…

    编程 2025-04-24
  • PHP导出Excel文件

    一、PHP导出Excel文件列宽调整 当我们使用PHP导出Excel文件时,有时需要调整单元格的列宽。可以使用PHPExcel类库中的setWidth方法来设置单元格的列宽。下面是…

    编程 2025-04-24
  • php扩展库初探

    一、什么是php扩展库? PHP扩展库(PHP extension)是一些用C语言编写的动态链接库,用于扩展PHP的功能。PHP扩展库使得PHP可以与各种数据库系统相连、SMTP、…

    编程 2025-04-23

发表回复

登录后才能评论