缩略图优化
最终我还是把缩略图加上,原本改了图片布局后又删掉了缩略图相关代码,但几天运行下来感觉加载原图还是不行,肉眼可见的慢……
经过深思熟虑还是加上缩略图吧,在运行看看效果,以前的缩略图都是固定宽高的,也就是常见的四四方方的小格子图片,这次改进了一下,毕竟布局是等高不等宽嘛,全都缩成比如 300*300 的也不行,横向的图会变得模胡。关于缩略图一直找不到最优的方案,缩放和裁剪都试过,当然不是不行,而是受技术所限吧。#瞎折腾/主题制作
后来在枫叶那看到关于腾讯云 oss
规则的文章,给我很大启发,脑海里分析后感觉能做出来。
由于我没有 oss 当图床,也不想用第三方储存图片,决定在现有的基础上改造,首先要解决灯箱问题,我没用第三方插件,也不想增加 a 标签来包裹 img,那么 src 为缩略图时原图地址怎么办,取了个巧,在 img 标签中增加一个 s 放原图地址。
通常缩略图都是放在另一个文件夹,这样一来就需要改动 js 增加几行,为了精简代码,这里就用到了腾讯云 oss
的规则将缩略图和原图放在一起,缩略图名称与原图一致,在缩略图后缀加!i 来区分,如jpg!i
。
发现浏览器将.jpg!i
识别为文件,虽然用 img 包裹住能显示,但直接输入地址就成了文件被下载到本地,不妥,查看枫叶的就不存在此问题,慒圈了不明白什么原理,也没人可以问,百度一番后大概猜到原因,怀疑是MIME 类型
.
试着修改看看,宝塔面板路径:www/server/nginx/conf/mime.types
增加需要的种类后保存并重启nginx
,刷新见证奇迹的时刻……
此时在看浏览器已将他识别为图片类型,这种形式还是头一次见,感觉好没见识呀,当我看到!i 是缩略图不要则是原图时惊掉了下巴,咋实现的?经过努力终于弄明白原理😀,或许这就是折腾的意义吧,虽然我不一定能记住,但始终是学到了,即使忘记当我在看到时还是有印像的。
存量无缩略图,写个脚本生成就好了!
<?php
// 指定要遍历的目录
$directory = '12/';
if (!is_dir($directory)) {
die("指定的目录不存在。");
}
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
if ($file == '.' || $file == '..') {
continue;
}
if (strpos($file, '!i')!== false) {
continue;
}
$filePath = $directory . '/' . $file;
if (is_file($filePath)) {
$info = pathinfo($file);
$fileName = $info['filename'];
$extension = $info['extension'];
$thumbnailFileName = $fileName . '.' . $extension . '!i';
$thumbnailFilePath = $directory . '/' . $thumbnailFileName;
if (!file_exists($thumbnailFilePath)) {
generateThumbnail($filePath, $thumbnailFilePath);
}
}
}
closedir($dir);
function generateThumbnail($sourceFilePath, $thumbnailFilePath) {
try {
$image = new Imagick($sourceFilePath);
$orientation = $image->getImageOrientation();
switch ($orientation) {
case Imagick::ORIENTATION_TOPLEFT:
break;
case Imagick::ORIENTATION_TOPRIGHT:
$image->flopImage();
break;
case Imagick::ORIENTATION_BOTTOMRIGHT:
$image->rotateImage(new ImagickPixel(), 180);
break;
case Imagick::ORIENTATION_BOTTOMLEFT:
$image->flopImage();
$image->rotateImage(new ImagickPixel(), 180);
break;
case Imagick::ORIENTATION_LEFTTOP:
$image->flopImage();
$image->rotateImage(new ImagickPixel(), -90);
break;
case Imagick::ORIENTATION_RIGHTTOP:
$image->rotateImage(new ImagickPixel(), 90);
break;
case Imagick::ORIENTATION_RIGHTBOTTOM:
$image->flopImage();
$image->rotateImage(new ImagickPixel(), 90);
break;
case Imagick::ORIENTATION_LEFTBOTTOM:
$image->rotateImage(new ImagickPixel(), -90);
break;
}
$image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
$width = $image->getImageWidth();
$height = $image->getImageHeight();
$maxWidth = 640;
if ($width > $maxWidth) {
// 根据原始宽高比计算新的高度
$newHeight = ($maxWidth / $width) * $height;
$image->thumbnailImage($maxWidth, $newHeight);
}
$image->writeImage($thumbnailFilePath);
$image->destroy();
} catch (ImagickException $e) {
error_log("生成缩略图时出错: " . $e->getMessage());
}
}