写在前面
之前尝试过直接用服务器跑,但是我可怜的阿里云学生机那1M带宽单图还好,多图加载10s+,后来用vultr的vps试了试,虽然带宽很大,国内访问依旧很慢。
突然想起都是用 jsdelivr 引用css和js文件,为什么不直接引用图片呢?
开始干活
1、首先找到想要的图片
2、改变图片分辨率+push到github
为了尽量让图片保持1920*1080的比例,用opencv调整分辨率,同时想要加快访问也可以压缩图片,不过我用的是无损压缩,相当于没变。
我直接将图片放在了本地git目录下,同时输出访问链接到 img.txt 中:
import os
import cv2
file_path = "D:\Git\git_res\CDN\images\\"
web_path = "https://cdn.jsdelivr.net/gh/SukiEva/CDN/images/"
def img_resize(image_path):
image = cv2.imread(file_path+image_path)
height, width = image.shape[0], image.shape[1]
# 设置新的图片分辨率框架
width_new = 1920
height_new = 1080
# 判断图片的长宽比率
if width / height >= width_new / height_new:
img = cv2.resize(image, (width_new, int(height * width_new / width)))
else:
img = cv2.resize(image, (int(width * height_new / height), height_new))
if ".jpg" in image_path:
cv2.imwrite(file_path+image_path, img, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
elif ".png" in image_path:
cv2.imwrite(file_path+image_path, img, [cv2.IMWRITE_PNG_COMPRESSION, 0])
if __name__ == '__main__':
filelist = os.listdir(file_path)
with open('E:\桌面\img.txt','w') as f:
for file in filelist:
img_resize(file)
f.write(web_path+file+'\n')
跑完代码将git同步到github中,同时桌面上的 img.txt 中也有了我们需要的链接。
3、写一个读取链接并重定向的 random.php:
<?php
//存有美图链接的文件名img.txt
filename = "img.txt";
if(!file_exists(filename)){
die('文件不存在');
}
//从文本获取链接
pics = [];fs = fopen(filename, "r");
while(!feof(fs)){
line=trim(fgets(fs));
if(line!=''){
array_push(pics, line);
}
}
//从数组随机获取链接pic = pics[array_rand(pics)];
//返回指定格式
type=_GET['type'];
switch(type){
//JSON返回
case 'json':
header('Content-type:text/json');
die(json_encode(['pic'=>pic]));
default:
die(header("Location: $pic"));
}
?>
4、将img.txt和random.php放到一个网站的目录下
5、访问 域名/random.php即可
比如我的 api:https://imapi.sukiu.top/random.php
也可以来我的网站看看运行效果:https://sukiu.top/
怎么样?是不是特别快!
Comments | 4 comments
$少了一个 符号 $
@1577791638 确实,博客显示的php代码有问题。。。和markdown的兼容不太好
为啥我没成功 太难了
@1577791638 emm,是网站代码块崩坏了,你去我的csdn上看php那部分代码 https://blog.csdn.net/qq_43640009/article/details/107945584