首页 > 解决方案 > 为什么加载需要这么长时间?

问题描述

基本上我试图显示从 FTP 下载的图像及其预览到下拉列表。好吧,我做到了,但我最近注意到大图像以全尺寸加载,并且网站在动画和东西上变得非常笨拙(并且也是第一次加载它)。然后我写了下面的代码,灵感来自互联网的各种来源。我设法让它工作,但现在网站加载速度更慢。怎么了?我是否放弃了这个想法,每次上传图像时都将预览上传到我的 FTP,还是有办法加快速度?

function endsWith($haystack, $needle) {
  $length = strlen($needle);
  if ($length == 0) {
    return true;
  }

  return (substr($haystack, -$length) === $needle);
}

function resize_image($file, $w) {
  list($width, $height) = getimagesize($file);
  $newwidth = $w;
  $newheight = ($w * $height) / $width;
  if (endsWith($file, '.png')) {
    $src = imagecreatefrompng($file);
  } else if (endsWith($file, '.jpeg') || endsWith($file, '.jpg')) {
    $src = imagecreatefromjpeg($file);
  } else if (endsWith($file, '.webp')) {
    $src = imagecreatefromwebp($file);
  } else if (endsWith($file, '.gif')) {
    $src = imagecreatefromgif($file);
  }
  $dst = imagecreatetruecolor($newwidth, $newheight);
  imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

  return $dst;
}

$images = scandir(__DIR__.
  '/'.
  'uploads/'.$_SESSION['id']);
$images = array_values(array_diff($images, array('.', '..', 'comments')));

for ($i = 0; $i < count($images); $i++) {
  $img = $images[$i];
  $id = $_SESSION['id'];
  $imga = resize_image(__DIR__.
    '/'.
    'uploads/'.$_SESSION['id'].
    '/'.$img, 100);
  ob_start();
  imagejpeg($imga, NULL, 100);
  imagedestroy($imga);
  $imgb = ob_get_clean();
  $imgb = base64_encode($imgb);
echo << EOL;
  <option value="$img" data-icon="data:image/jpeg;base64,$imgb">$img</option>
EOL;
}

输出到 div:

<div class="your-files input-field col s12 m6" id="your-avatars">
    <select class="icons">
        <option selected disabled value="default">Wybierz obrazek...</option>
        <!-- here comes the PHP output -->
    </select>
</div>

标签: phphtml

解决方案


推荐阅读