recherche

Maison  >  Questions et réponses  >  le corps du texte

php - 有什么方法将上传的图片将图片大小变小而且不失真

如题,PHP有什么办法处理图片 变小 而不会很失真
可在上传前处理 或上传后处理
有朋友做过么 小白求解答 谢谢

ringa_leeringa_lee2907 Il y a quelques jours701

répondre à tous(2)je répondrai

  • 巴扎黑

    巴扎黑2017-04-11 10:35:19

    等比例缩放就好了 上传成功后,可以使用php原生的GD库(扩者框架里写好的方法)

    GD库方法:

    这里时以前写的封装成的函数 主要逻辑在 : 3. 计算缩放后的图片尺寸

    *形参列表:picname:图片文件名称

    • maxWidth 图片被缩放后的最大宽度

    • maxHeight 图片被缩放后的最大高度

    • pre 缩放后的图片名前缀,默认为"s_" 根据需要改
      *返回值:布尔值表示成功与否。

    `function imageResize($picname,$path,$maxWidth,$maxHeight,$pre="s_"){

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    <code>$path = rtrim($path,"/")."/";

    //1获取被缩放的图片信息

    $info = getimagesize($path.$picname);

    //获取图片的宽和高

    $width = $info[0];

    $height = $info[1];

     

    //2根据图片类型,使用对应的函数创建画布源。

    switch($info[2]){

        case 1: //gif格式

            $srcim = imagecreatefromgif($path.$picname);

            break;

        case 2: //jpeg格式

            $srcim = imagecreatefromjpeg($path.$picname);

            break;

        case 3: //png格式

            $srcim = imagecreatefrompng($path.$picname);

            break;

       default:

            return false;

            //die("无效的图片格式");

            break;

    }

    //3. 计算缩放后的图片尺寸

    if($maxWidth/$width<$maxHeight/$height){

        $w = $maxWidth;

        $h = ($maxWidth/$width)*$height;

    }else{

        $w = ($maxHeight/$height)*$width;

        $h = $maxHeight;

    }

    //4. 创建目标画布

    $dstim = imagecreatetruecolor($w,$h);

     

    //5. 开始绘画(进行图片缩放)

    imagecopyresampled($dstim,$srcim,0,0,0,0,$w,$h,$width,$height);

     

    //6. 输出图像另存为

    switch($info[2]){

        case 1: //gif格式

            imagegif($dstim,$path.$pre.$picname);

            break;

        case 2: //jpeg格式

            imagejpeg($dstim,$path.$pre.$picname);

            break;

        case 3: //png格式

            imagepng($dstim,$path.$pre.$picname);

            break;

    }

     

    //7. 释放资源

    imagedestroy($dstim);

    imagedestroy($srcim);

     

    return true;</code>

    }
    `

    répondre
    0
  • 巴扎黑

    巴扎黑2017-04-11 10:35:19

    github

    https://github.com/search?o=d...

    répondre
    0
  • Annulerrépondre