山林小树 2019-04-15 09:07 采纳率: 0%
浏览 1634

PHP 如何进行图片压缩后上传

我在网上找到了一段代码可以实现利用缩放减小图片大小,但是如何对缩放后的图片进行上传?
<?php
header("content-type:image/png");
/**

  • @param $imagedata 图像数据
  • @param $width 缩放宽度
  • @param $height 缩放高度
  • @param int $per 缩放比例,为0不缩放,>0忽略参数2、3的宽高
  • @return bool|string
    */
    function image_resize($imagedata, $width, $height, $per = 0.5) {
    // 1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP,7 = TIFF(intel byte order),8 = TIFF(motorola byte order),9 = JPC,10 = JP2,11 = JPX,12 = JB2,13 = SWC,14 = IFF,15 = WBMP,16 = XBM

    // 获取图像信息
    list($bigWidth, $bigHight, $bigType) = getimagesizefromstring($imagedata);

    // 缩放比例
    if ($per > 0) {
    $width = $bigWidth * $per;
    $height = $bigHight * $per;
    }

    // 创建缩略图画板
    $block = imagecreatetruecolor($width, $height);

    // 启用混色模式
    imagealphablending($block, false);

    // 保存PNG alpha通道信息
    imagesavealpha($block, true);

    // 创建原图画板
    $bigImg = imagecreatefromstring($imagedata);

    // 缩放
    imagecopyresampled($block, $bigImg, 0, 0, 0, 0, $width, $height, $bigWidth, $bigHight);

    // 生成临时文件名
    $tmpFilename = tempnam(sys_get_temp_dir(), 'image_');

    // 保存
    switch ($bigType) {
    case 1: imagegif($block, $tmpFilename);
    break;

    case 2: imagejpeg($block, $tmpFilename);
        break;
    
    case 3: imagepng($block, $tmpFilename);
        break;
    

    }

    // 销毁
    imagedestroy($block);

    $image = file_get_contents($tmpFilename);

    unlink($tmpFilename);

    return $image;
    }

// 缩放图像
echo image_resize(file_get_contents('C:\Users\10633\Pictures\Camera Roll\微信图片_20180614094713.jpg'), 100, 200);

?>

  • 写回答

1条回答

  • lsswear 2023-06-13 15:56
    关注

    读取文件内容,内容为base64字符串然后上传。就是说接口读取的base64,后用数据创建文件。
    或者类似于表单提交,传文件。可以用curl 或者apifox这种第三方软件。接口接收文件对象,然后操作。
    原理就是本地有文件(原文件或者压缩后文件),作为表单数据或者字符串数据上传。
    文件上传得调php.ini配置,上传的缓存大小和php处理的缓存大小,这个百度下就好。

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器