标签: code

  • 【网站】在WP区块中添加CSS+JS动画

    类似如下效果:

    H armony

    O ptimize

    N ature

    E nergy

    S ustainability

    S olutions

    ALL In

    HONESS.

    可以直接在区块代码编辑器中进行添加。

    <p class="has-text-align-left has-text-color"
        style="color:#ffffff61;font-size:72px;font-style:normal;font-weight:700;letter-spacing:-2px;line-height:1;text-transform:uppercase">
        <em>H</em> <strong>armony</strong></p>

    例如以上是第一行动画文字的代码,因为在区块中我们给不同的文字设定了不同的标签,我们可以直接在代码中修改后面strong标签的类,改成如下:

    <p class="has-text-align-left has-text-color"
        style="color:#ffffff61;font-size:72px;font-style:normal;font-weight:700;letter-spacing:-2px;line-height:1;text-transform:uppercase">
        <em>H</em> <strong class="change-word">armony</strong></p>

    这样我们就可以利用CSS+JS动画实现该标签的动画效果。

    CSS:

    <style>
        .change-word {
            display: inline-block;
            transition: opacity 0.4s ease-in-out, transform 0.4s ease-in-out;
        }
        .hidden {
            opacity: 0;
            transform: translateY(-10px);
        }
    </style>

    JS:

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const words = [
                ["armony", "ope", "ealth", "appiness"], // H
                ["ptimize", "pportunity", "rganic", "vergreen"], // O
                ["ature", "urture", "eeds", "urturing"], // N
                ["nergy", "arth", "cology", "nvironment"], // E
                ["ustainability", "ynergy", "upport", "olutions"], // S
                ["olutions", "trategy", "uccess", "ymbiosis"] // S
            ];
    
            function changeWord(index, element, delay) {
                setTimeout(() => {
                    element.classList.add("hidden"); // 先隐藏
                    setTimeout(() => {
                        let nextWord = words[index].shift();
                        words[index].push(nextWord);
                        element.textContent = nextWord;
                        element.classList.remove("hidden"); // 显示
                    }, 400);
                }, delay);
            }
    
            function startAnimation() {
                let elements = document.querySelectorAll(".change-word");
                let delay = 100;
                elements.forEach((el, index) => {
                    setInterval(() => changeWord(index, el, index * delay), 2500);
                });
            }
    
            startAnimation();
        });
    </script>
  • 【网站】让WordPress封面区块的视频背景支持在微信环境下自动切换为照片

    移动版本的微信,在其内置的微信WEB环境中,对视频播放有很多限制,如果我们的封面区块想设置视频,就会出现无法加载播放的情况。

    为了解决这个问题,我去看了一下一些大厂的做法,当然大厂用的肯定不是WP,不过思路是可以借鉴的。

    华为的做法是用一个JS来判断是否是微信环境,如果是微信环境则切换到图片。OPPO的做法更加直接,他们直接用图片+动画的形式解决了视频这个问题,emm通用性确实刚刚的。

    那么我们在WP下,使用原版的封面区块是否可以进行类似的切换呢?也是可以的,原理是在区块代码中插入一个图片,利用一个简单的IF判断来实现微信环境下的自动切换。

    具体代码如下:

    <!-- wp:cover {"url":"//默认图片地址","id":588,"dimRatio":50,"overlayColor":"contrast","isUserOverlayColor":true,"backgroundType":"video","minHeight":840,"minHeightUnit":"px","isDark":false,"className":"main-container","layout":{"type":"constrained"}} -->
    <div class="wp-block-cover is-light main-container" style="min-height:840px">
        <span aria-hidden="true" class="wp-block-cover__background has-contrast-background-color has-background-dim"></span>
    
        <!-- 视频背景,添加 id="background-video" -->
        <video id="background-video" class="wp-block-cover__video-background intrinsic-ignore" autoplay muted loop playsinline 
            src="//视频地址" data-object-fit="cover">
        </video>
    
        <!-- 备用静态图片,默认隐藏 -->
        <img id="background-image" src="//图片地址" 
            alt="Background Image" style="display:none; width: 100%; height: 100%; object-fit: cover; position: absolute; top: 0; left: 0;">
    
        <div class="wp-block-cover__inner-container">
            <!-- 可添加文本或其他内容 -->
        </div>
    </div>
    <!-- /wp:cover -->
    
    <script>
    document.addEventListener("DOMContentLoaded", function () {
        function isWeChatBrowser() {
            return /MicroMessenger/i.test(navigator.userAgent);
        }
    
        if (isWeChatBrowser()) {
            let video = document.getElementById("background-video");
            let image = document.getElementById("background-image");
    
            if (video && image) {
                video.style.display = "none"; // 隐藏视频
                image.style.display = "block"; // 显示备用图片
            }
        }
    });
    </script>
    
  • 【网站】WordPress中如何获得无间隔的区块

        "spacing": {
            "blockGap": "1.2rem",
            "padding": {
                "left": "var:preset|spacing|50",
                "right": "var:preset|spacing|50"
            }
        },

    6.X版本的Wordpress中,区块之间会有一个默认1.2rem的间隔,这个间隔在页眉页脚设置中会与其他不同色彩的区块产生非常显眼的割裂,或者同一种非白色区块中间产生间隔缝隙。

    如何修改这个问题?很简单,我们可以在主题样式和区块设置 (theme.json)中进行更改,去掉这个间隔,让我们的区块背景更加融合或者分离的更明显,具体如上代码,找到 “spacing” 中的 “blockGap” 部分,将预设的 “1.2rem” 改为null即可(不用带引号),修改完毕的代码如下所示↓

    修改完毕后最好检查一下页面是否有其他区块被影响,目前观察容易受到影响的有导航栏,可以在其单独的样式中针对性调整区块间隔。

        "spacing": {
            "blockGap": null,
            "padding": {
                "left": "var:preset|spacing|50",
                "right": "var:preset|spacing|50"
            }
        },
  • 【Python】提取视频画面并生成PPT

    比较笨的方法,用来提取PPT课程视频画面,并生成对应的PPT,代码检测黑屏但没有检测白屏,没有检测重复画面(因为有些人讲课会来回翻PPT),因此还有优化空间。内存占用会逐渐增多,不过测试没有出现崩溃的情况。

    PS:做完发现可以直接问讲课人要PPT原件,我,,,

    import cv2
    import os
    import numpy as np
    from pptx import Presentation
    from pptx.util import Inches
    from skimage.metrics import structural_similarity as ssim
    import tkinter as tk
    from tkinter import filedialog, messagebox
    
    # 选择视频和输出目录
    def select_video_and_output():
        video_path = filedialog.askopenfilename(title="选择视频文件", filetypes=[("MP4 files", "*.mp4")])
        if not video_path:
            messagebox.showwarning("选择视频", "未选择视频文件")
            return None, None
        
        output_dir = filedialog.askdirectory(title="选择输出目录")
        if not output_dir:
            messagebox.showwarning("选择输出目录", "未选择输出目录")
            return None, None
    
        pptx_path = os.path.join(output_dir, "output_presentation.pptx")
        return video_path, pptx_path
    
    # 处理视频并生成 PPT
    def process_video_to_ppt(video_path, pptx_path):
        os.makedirs("ppt_images", exist_ok=True)
        
        cap = cv2.VideoCapture(video_path)
        _, prev_frame = cap.read()
        prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)
    
        frame_count = 0
        slide_count = 0
        images = []
        similarity_threshold = 0.95  # 提高 SSIM 阈值,减少相似图片
        brightness_threshold = 10  # 黑屏检测(平均亮度 < 10 认为是黑屏)
    
        def process_frame(frame):
            """ 计算 SSIM 相似度,判断是否保存该帧 """
            nonlocal prev_gray, slide_count
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            score = ssim(prev_gray, gray)
    
            # 计算平均亮度,过滤黑屏
            avg_brightness = np.mean(gray)
            if avg_brightness < brightness_threshold:
                return  # 跳过黑屏帧
    
            if score < similarity_threshold:  
                img_path = os.path.join("ppt_images", f"slide_{slide_count}.jpg")
    
                # 确保不同的幻灯片才保存
                if len(images) == 0 or images[-1] != img_path:  
                    cv2.imwrite(img_path, frame)
                    images.append(img_path)
                    slide_count += 1
                    prev_gray = gray  # 只在确认变化时更新参考帧
    
        while cap.isOpened():
            ret, frame = cap.read()
            if not ret:
                break
    
            # 仅每隔 15 帧处理一次
            if frame_count % 15 == 0:
                process_frame(frame)
    
            frame_count += 1
    
        cap.release()
        # cv2.destroyAllWindows()
    
        # 创建 PPT
        prs = Presentation()
        for img in images:
            slide = prs.slides.add_slide(prs.slide_layouts[5])  # 空白幻灯片
            left, top, width, height = Inches(0), Inches(0), Inches(10), Inches(7.5)
            slide.shapes.add_picture(img, left, top, width, height)
    
        prs.save(pptx_path)
        messagebox.showinfo("完成", f"PPTX 生成完成: {pptx_path}")
    
    # 主函数
    def main():
        root = tk.Tk()
        root.withdraw()  # 隐藏主窗口
        video_path, pptx_path = select_video_and_output()
        if video_path and pptx_path:
            process_video_to_ppt(video_path, pptx_path)
    
    if __name__ == "__main__":
        main()
    
  • 【网站】通过模板函数及WP设置文件配置SMTP邮件服务

    为什么我们需要配置邮件服务?

    第一,配置邮件服务可以避免WP中勾选邮件通知但是后台未配置导致的评论发送延迟。第二,可以让找回密码等服务可用。(也就是你要是没有配置服务所谓的密码找回是无效的,当然有自己服务器的就无所谓了,有更加快捷的方法重置密码)

    服务器注意事项

    前提1:服务器端需要开放465端口。

    前提2:防火墙开放465端口。

    采用465端口是因为云服务器的提供商普遍禁25端口,尝试解封了一下没有什么卵用。

    因此我们可以使用465端口进行邮件服务,国内可以直接使用QQ邮箱,在设置中获取授权码、服务器地址等配置基础信息。Hotmail需要配置另外一套验证机制,有点麻烦了,还是建议使用QQ邮箱,响应速度很快。

    配置步骤

    一般分为两个步骤,对wp-config文件和function模板函数进行修改,其实也可以直接配置模板函数,不过理论上通过WP配置文件配置更加安全,因为权限更高。

    WP-Config:

    // SMTP 配置
    define('HOST', 'smtp.qq.com');// smtp服务器
    define('PORT', 465);// 端口
    define('USERNAME', 'email@qq.com'); // 设置邮箱
    define('PASSWORD', 'password'); // 授权码
    define('SECURE', 'ssl'); // ssl
    define('FROM', 'your_qq_email@qq.com'); // 邮箱
    define('FROM_NAME', 'Name'); // 发件人名称

    模板函数:

    function custom_phpmailer_settings($phpmailer) {
    $phpmailer->isSMTP();
    $phpmailer->Host = HOST;
    $phpmailer->SMTPAuth = true;
    $phpmailer->Port =PORT;
    $phpmailer->Username = USERNAME;
    $phpmailer->Password = PASSWORD;
    $phpmailer->SMTPSecure = SECURE;
    $phpmailer->From = FROM;
    $phpmailer->FromName = FROM_NAME;
    }
    add_action('phpmailer_init', 'custom_phpmailer_settings');
  • 【Python】使用cwebp、gif2webp、exiftool实现保留exif信息的WebP转换

    此前写了个使用cwebp、gif2webp的脚本,但是由于cwebp目前在win的元数据提取存在问题,因此我们可以使用已经支持exif提取和写入的exiftool进行最后一步的转换,这样我们的图片压缩、转码都在官方库得以实现。

    前置条件:

    cwebp、gif2webp、exiftool三个组件都注册到系统环境变量。python则使用pil库用于分辨率获取。

    实现效果:

    使用pil库对分辨率进行获取,但是不介入压缩过程,因为cwebp目前没法获取图片分辨率,使用pil库进行是否执行resize的判断。

    使用cwebp处理静态png、jpg,使用gif2webp处理gif图,启用mt多线程,压缩质量85,resize到2560最长、宽边,exiftool采用”-overwrite_original”来避免生成两个图片。

    测试效果:

    该图片原图7M多,压缩质量选择85,可能由于细节较为丰富,压缩到WebP大小仍为1M左右,还是比较大,不过细节保留充分,同时保留了EXIF信息。

    import tkinter as tk
    from tkinter import filedialog, messagebox
    import os
    import subprocess
    from PIL import Image
    
    def validate_file(input_path):
        input_path = os.path.abspath(input_path)
        if not os.path.exists(input_path):
            raise FileNotFoundError(f"文件 {input_path} 不存在,请检查路径。")
        return input_path
    
    def get_resized_dimensions(width, height, max_size):
        if width > height:
            new_width = max_size
            new_height = int((new_width / width) * height)
        else:
            new_height = max_size
            new_width = int((new_height / height) * width)
        return new_width, new_height
    
    def convert_image(input_path, output_path, new_width=None, new_height=None):
        try:
            file_extension = os.path.splitext(input_path)[1].lower()
            if file_extension == ".gif":
                command = ["gif2webp","mt", input_path, "-o", output_path]
            else:
                if new_width and new_height:
                    command = ["cwebp","mt", "-q", "85", "-resize", str(new_width), str(new_height), input_path, "-o", output_path]
                else:
                    command = ["cwebp","mt", "-q", "85", input_path, "-o", output_path]
            subprocess.run(command, check=True)
        except subprocess.CalledProcessError as e:
            raise RuntimeError(f"转换工具运行出错: {e}")
    
    def embed_exif(input_path, output_path):
        try:
            command = ["exiftool", "-overwrite_original", "-tagsfromfile", input_path, "-all:all", output_path]
            subprocess.run(command, check=True)
        except subprocess.CalledProcessError as e:
            raise RuntimeError(f"EXIF 数据嵌入失败: {e}")
    
    def convert_to_webp(input_path, max_size=2560):
        try:
            # 验证文件路径
            input_path = validate_file(input_path)
            output_path = os.path.splitext(input_path)[0] + ".webp"
    
            # 使用 PIL 获取图像分辨率
            with Image.open(input_path) as img:
                width, height = img.size
                if width <= max_size and height <= max_size:
                    convert_image(input_path, output_path)
                else:
                    new_width, new_height = get_resized_dimensions(width, height, max_size)
                    convert_image(input_path, output_path, new_width, new_height)
    
            # 嵌入 EXIF 数据
            embed_exif(input_path, output_path)
    
            return f"图片已转换并保存为 {output_path}"
    
        except (subprocess.CalledProcessError, FileNotFoundError) as e:
            return str(e)
        except Exception as e:
            return f"处理文件时发生错误: {e}"
    
    def select_files():
        file_paths = filedialog.askopenfilenames(
            title="选择图片文件",
            filetypes=[("*所有图片格式", "*.jpg;*.jpeg;*.png;*.gif"),
                       ("JPEG 图片", "*.jpg;*.jpeg"),
                       ("PNG 图片", "*.png"),
                       ("GIF 图片", "*.gif")]
        )
        if file_paths:
            for path in file_paths:
                file_listbox.insert(tk.END, path)
    
    def convert_and_save_batch():
        files = file_listbox.get(0, tk.END)
        if not files:
            messagebox.showerror("错误", "请选择至少一个图片文件!")
            return
    
        results = [convert_to_webp(file_path) for file_path in files]
        messagebox.showinfo("完成", "\n".join(results))
    
    def clear_list():
        file_listbox.delete(0, tk.END)
    
    root = tk.Tk()
    root.title("批量图片转换为 WebP 工具")
    root.geometry("600x400")
    
    frame = tk.Frame(root)
    frame.pack(pady=10, padx=10, fill=tk.BOTH, expand=True)
    
    scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL)
    file_listbox = tk.Listbox(frame, selectmode=tk.EXTENDED, yscrollcommand=scrollbar.set)
    scrollbar.config(command=file_listbox.yview)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    file_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    
    button_frame = tk.Frame(root)
    button_frame.pack(pady=10)
    
    select_button = tk.Button(button_frame, text="选择文件", command=select_files, width=15)
    select_button.grid(row=0, column=0, padx=5)
    
    clear_button = tk.Button(button_frame, text="清空列表", command=clear_list, width=15)
    clear_button.grid(row=0, column=1, padx=5)
    
    convert_button = tk.Button(button_frame, text="批量转换", command=convert_and_save_batch, width=15)
    convert_button.grid(row=0, column=2, padx=5)
    
    root.mainloop()
    
  • 【Python】使用WebP官方库进行WebP转换

    此前的代码使用了Pillow库集成的库,这次使用WebP官方库,对GIF、PNG的处理也比较友好。需要添加WebP的库到系统环境变量后使用。

    功能实现:

    代码使用cwebp、gif2webp两种方式转换不同的格式图片,使用库本身的压缩分辨率方法,压缩图片到2560最长、宽。

    对于gif,该代码可以实现对原图动态的保持,此前使用pillow库则可以设定gif的持续或者最后一帧静帧。

    遗憾:

    没有能够传递exif,win平台中cwebp压根没法有效传递exif信息,显示——Warning: only ICC profile extraction is currently supported on this platform!元数据只有ICC才能支持传递,所以只依靠cwebp是没法很好在win中进行转换的。

    这个问题采用exiftool进行了解决,下篇文章可以看到。

    import tkinter as tk
    from tkinter import filedialog, messagebox
    import os
    import subprocess
    from PIL import Image
    
    def validate_file(input_path):
        input_path = os.path.abspath(input_path)
        if not os.path.exists(input_path):
            raise FileNotFoundError(f"文件 {input_path} 不存在,请检查路径。")
        return input_path
    
    def get_resized_dimensions(width, height, max_size):
        if width > height:
            new_width = max_size
            new_height = int((new_width / width) * height)
        else:
            new_height = max_size
            new_width = int((new_height / height) * width)
        return new_width, new_height
    
    # 使用 cwebp 或 gif2webp 进行转换
    def convert_image(input_path, output_path, new_width=None, new_height=None, cwebp_metadata="none", gif2webp_metadata="none"):
        try:
            file_extension = os.path.splitext(input_path)[1].lower()
            if file_extension == ".gif":
                command = ["gif2webp", "-metadata", gif2webp_metadata, "-mt", input_path, "-o", output_path]
            else:
                if new_width and new_height:
                    command = ["cwebp", "-q", "85", "-resize", str(new_width), str(new_height), "-metadata", cwebp_metadata, "-mt", input_path, "-o", output_path]
                else:
                    command = ["cwebp", "-q", "85", "-metadata", cwebp_metadata, "-mt", input_path, "-o", output_path]
            subprocess.run(command, check=True)
        except subprocess.CalledProcessError as e:
            raise RuntimeError(f"转换工具运行出错: {e}")
    
    def convert_to_webp(input_path, max_size=2560, cwebp_metadata="none", gif2webp_metadata="none"):
        try:
            # 验证文件路径
            input_path = validate_file(input_path)
            output_path = os.path.splitext(input_path)[0] + ".webp"
    
            # 使用 PIL 获取图像分辨率
            with Image.open(input_path) as img:
                width, height = img.size
                if width <= max_size and height <= max_size:
                    convert_image(input_path, output_path, cwebp_metadata=cwebp_metadata, gif2webp_metadata=gif2webp_metadata)
                else:
                    new_width, new_height = get_resized_dimensions(width, height, max_size)
                    convert_image(input_path, output_path, new_width, new_height, cwebp_metadata=cwebp_metadata, gif2webp_metadata=gif2webp_metadata)
    
            return f"图片已转换并保存为 {output_path}"
    
        except (subprocess.CalledProcessError, FileNotFoundError) as e:
            return str(e)
        except Exception as e:
            return f"处理文件时发生错误: {e}"
    
    def select_files():
        file_paths = filedialog.askopenfilenames(
            title="选择图片文件",
            filetypes=[("*所有图片格式", "*.jpg;*.jpeg;*.png;*.gif"),
                       ("JPEG 图片", "*.jpg;*.jpeg"),
                       ("PNG 图片", "*.png"),
                       ("GIF 图片", "*.gif")]
        )
        if file_paths:
            for path in file_paths:
                file_listbox.insert(tk.END, path)
    
    def convert_and_save_batch():
        files = file_listbox.get(0, tk.END)
        if not files:
            messagebox.showerror("错误", "请选择至少一个图片文件!")
            return
    
        cwebp_metadata = "exif"  # 设置cwebp要复制的元数据类型为exif
        gif2webp_metadata = "xmp"  # 设置gif2webp要复制的元数据类型为xmp
        results = [convert_to_webp(file_path, cwebp_metadata=cwebp_metadata, gif2webp_metadata=gif2webp_metadata) for file_path in files]
        messagebox.showinfo("完成", "\n".join(results))
    
    def clear_list():
        file_listbox.delete(0, tk.END)
    
    # 创建主窗口
    root = tk.Tk()
    root.title("批量图片转换为 WebP 工具")
    root.geometry("600x400")
    
    frame = tk.Frame(root)
    frame.pack(pady=10, padx=10, fill=tk.BOTH, expand=True)
    
    scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL)
    file_listbox = tk.Listbox(frame, selectmode=tk.EXTENDED, yscrollcommand=scrollbar.set)
    scrollbar.config(command=file_listbox.yview)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    file_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    
    button_frame = tk.Frame(root)
    button_frame.pack(pady=10)
    
    select_button = tk.Button(button_frame, text="选择文件", command=select_files, width=15)
    select_button.grid(row=0, column=0, padx=5)
    
    clear_button = tk.Button(button_frame, text="清空列表", command=clear_list, width=15)
    clear_button.grid(row=0, column=1, padx=5)
    
    convert_button = tk.Button(button_frame, text="批量转换", command=convert_and_save_batch, width=15)
    convert_button.grid(row=0, column=2, padx=5)
    
    root.mainloop()
    
  • 【Python】使用PIL库进行多格式批量转换WebP并压缩分辨率

    网站将逐步切换到WebP格式图片,今天捣鼓了插件在服务器端替换图片,但WP的媒体库却怎么都搞不定了,媒体库会自动生成很多缩略图用于不同的场景,我不想碰它的缩略图生成效果,因此只写单一的转换代码是没法做出完整的效果的。

    退而求其次使用本地对图片进行处理,该脚本使用PIL库,图片分辨率限制为2560最长/宽,可以处理带透明通道的图片,也可以处理GIF,用下来效果还不错。

    1月8日更新:

    【Python】使用WebP官方库进行WebP转换
    【Python】使用cwebp、gif2webp、exiftool实现保留exif信息的WebP转换

    import tkinter as tk
    from tkinter import filedialog, messagebox
    from PIL import Image, ImageSequence
    import os
    
    def resize_image(img):
        max_size = 2560
        width, height = img.size
    
        if width > max_size or height > max_size:
            if width > height:
                new_width = max_size
                new_height = int((new_width / width) * height)
            else:
                new_height = max_size
                new_width = int((new_height / height) * width)
            
            img = img.resize((new_width, new_height), Image.LANCZOS)
        
        return img
    
    def convert_to_webp(input_path):
        try:
            file_extension = os.path.splitext(input_path)[1].lower()
            output_path = os.path.splitext(input_path)[0] + ".webp"
    
            if not os.path.exists(input_path):
                raise FileNotFoundError(f"文件 {input_path} 不存在,请检查路径。")
    
            if file_extension == '.webp':
                return f"文件 {input_path} 已是 WebP 格式,无需转换。"
    
            with Image.open(input_path) as img:
                if file_extension in ['.gif'] and getattr(img, "is_animated", False):
                    frames = []
                    durations = []
                    for frame in ImageSequence.Iterator(img):
                        # 处理透明度
                        if frame.mode == "P":
                            frame = frame.convert("RGBA")
                        
                        # 转换帧为 RGBA 并存储
                        new_frame = frame.copy()
                        frames.append(new_frame)
                        durations.append(frame.info.get('duration', 100))
    
                    # 重复最后一帧
                    if len(frames) > 1:
                        durations[-1] = max(durations[-1], 100) 
    
                    # 保存为动态 WebP
                    frames[0].save(
                        output_path,
                        format="WEBP",
                        save_all=True,
                        append_images=frames[1:],
                        duration=durations,
                        loop=img.info.get('loop', 0),  # 循环次数
                        transparency=0,  # 确保透明度保留
                        quality=85
                    )
                else:
                    # 静态图片处理
                    if img.mode == "P":
                        if "transparency" in img.info:
                            img = img.convert("RGBA")
                        else:
                            img = img.convert("RGB")
    
                    img = resize_image(img)
    
                    if img.mode != "RGBA":
                        img = img.convert("RGBA")
    
                    img.save(output_path, format="WEBP", quality=85)
    
            return f"图片已转换并保存为 {output_path}"
        except Exception as e:
            return f"处理文件时发生错误: {e}"
    
    
    def select_files():
        file_paths = filedialog.askopenfilenames(
            title="选择图片文件",
            filetypes=[("所有图片格式", "*.jpg;*.jpeg;*.png;*.gif;*.webp;*.bmp;*.tiff"), 
                       ("JPEG 图片", "*.jpg;*.jpeg"),
                       ("PNG 图片", "*.png"),
                       ("GIF 图片", "*.gif"),
                       ("WebP 图片", "*.webp"),
                       ("BMP 图片", "*.bmp"),
                       ("TIFF 图片", "*.tiff")]
        )
        if file_paths:
            for path in file_paths:
                file_listbox.insert(tk.END, path)
    
    def convert_and_save_batch():
        files = file_listbox.get(0, tk.END)
        if not files:
            messagebox.showerror("错误", "请选择至少一个图片文件!")
            return
    
        results = []
        for file_path in files:
            result = convert_to_webp(file_path)
            results.append(result)
    
        messagebox.showinfo("完成", "\n".join(results))
    
    def clear_list():
        file_listbox.delete(0, tk.END)
    
    root = tk.Tk()
    root.title("批量图片转换为 WebP 工具")
    root.geometry("600x400")
    
    frame = tk.Frame(root)
    frame.pack(pady=10, padx=10, fill=tk.BOTH, expand=True)
    
    scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL)
    file_listbox = tk.Listbox(frame, selectmode=tk.EXTENDED, yscrollcommand=scrollbar.set)
    scrollbar.config(command=file_listbox.yview)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    file_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    
    button_frame = tk.Frame(root)
    button_frame.pack(pady=10)
    
    select_button = tk.Button(button_frame, text="选择文件", command=select_files, width=15)
    select_button.grid(row=0, column=0, padx=5)
    
    clear_button = tk.Button(button_frame, text="清空列表", command=clear_list, width=15)
    clear_button.grid(row=0, column=1, padx=5)
    
    convert_button = tk.Button(button_frame, text="批量转换", command=convert_and_save_batch, width=15)
    convert_button.grid(row=0, column=2, padx=5)
    
    root.mainloop()
  • 【自然笔记】通过ECharts建立观鸟图表

    (!该内容目前只做测试,分类未经过严格验证)

    通过模板函数引入ECharts的js,不过这次限制了只有“Echarts”标签的文章加载,避免影响其他界面的加载速度。

    效果如上:采用了矩形树图+旭日图,感觉旭日图更加醒目,通过点击标题来切换图表类型。

    <div id="chart-title" style="text-align: center; font-size: 20px; margin-top: 10px; cursor: pointer; color: #007BFF;">
        切换图表类型
    </div>
      document.getElementById('chart-title').addEventListener('click', function () {
                    if (currentOption === 'treemap') {
                        myChart.setOption(sunburstOption);
                        currentOption = 'sunburst';
                    } else {
                        myChart.setOption(treeMapOption);
                        currentOption = 'treemap';
                    }
                });
            });

  • 【WP插件】通过插件形式为WP导入回到顶部功能

    网站此前用的回到顶部按钮是通过插件市场中的插件实现,效果还不错,不过功能比较单一。

    我在其他的博客中看到了一个可以在页面下拉过程中实现当前页面进度的回顶按钮,觉得实用性很棒,因此尝试通过页面脚本的形式导入。

    但是这种方式过于低效,且没法很好自定义,所以便尝试是否可以通过插件的形式导入功能,通过和GPT的一番交流,大致明白了WP插件的制作过程。

    WP的插件可以通过Zip文件导入,其中的结构为:

    backtop/
    ├── assets/
    │ ├── backtop.css
    │ └── backtop.js
    ├── backtop.php
    └── readme.txt (可选)

    其中backtop.php是插件的核心文件,包含了插件的主要功能和初始化代码。

    backtop.css为样式表,js则是JavaScript 文件,写交互逻辑使用。

    参考代码:

    PHP:

    <?php
    /*
    Plugin Name: 写你的插件名称
    Description: 描述
    Version: 版本号
    Author: 作者
    Author URI: https://wanxuefeiyang.cn
    License: GPL2
    */
    
    // Enqueue CSS and JS,注意地址
    function backtop_enqueue_assets() {
        wp_enqueue_style('backtop-style', plugin_dir_url(__FILE__) . 'assets/backtop.css');
        wp_enqueue_script('backtop-script', plugin_dir_url(__FILE__) . 'assets/backtop.js', [], false, true);
    
        $options = get_option('backtop_options');
        wp_localize_script('backtop-script', 'backTopOptions', [
            'position' => $options['position'] ?? 'bottom-right',
            'color' => $options['color'] ?? '#000000',
            'size' => $options['size'] ?? '40px',
            'shape' => $options['shape'] ?? 'circle',
            'margin' => $options['margin'] ?? '20px 20px'
        ]);
    }
    add_action('wp_enqueue_scripts', 'backtop_enqueue_assets');
    
    // 插入 HTML
    function backtop_render_html() {
        echo '
        <div id="backtop-tool">
            <ul>
                <li id="backtop" class="hidden">
                    <span id="backtop-percentage">0%</span>
                </li>
            </ul>
        </div>';
    }
    add_action('wp_footer', 'backtop_render_html');
    
    // 设置页面,可以自定义一些内容
    function backtop_add_settings_page() {
        add_options_page(
            'BackTop Settings',
            'BackTop',
            'manage_options',
            'backtop-settings',
            'backtop_render_settings_page'
        );
    }
    add_action('admin_menu', 'backtop_add_settings_page');
    
    function backtop_render_settings_page() {
        ?>
        <div class="wrap">
            <h1>BackTop Settings</h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('backtop_options_group');
                do_settings_sections('backtop-settings');
                submit_button();
                ?>
            </form>
        </div>
        <?php
    }
    
    function backtop_register_settings() {
        register_setting('backtop_options_group', 'backtop_options', [
            'type' => 'array',
            'sanitize_callback' => 'backtop_sanitize_options',
            'default' => [
                'position' => 'bottom-right',
                'color' => '#000000',
                'size' => '40px',
                'shape' => 'circle',
                'margin' => '20px 20px'
            ],
        ]);
    
        add_settings_section('backtop_main_section', 'Main Settings', null, 'backtop-settings');
    
        add_settings_field('position', 'Position', 'backtop_position_field', 'backtop-settings', 'backtop_main_section');
        add_settings_field('color', 'Background Color', 'backtop_color_field', 'backtop-settings', 'backtop_main_section');
        add_settings_field('size', 'Button Size', 'backtop_size_field', 'backtop-settings', 'backtop_main_section');
        add_settings_field('shape', 'Shape', 'backtop_shape_field', 'backtop-settings', 'backtop_main_section');
        add_settings_field('margin', 'Margin', 'backtop_margin_field', 'backtop-settings', 'backtop_main_section');
    }
    add_action('admin_init', 'backtop_register_settings');
    
    function backtop_position_field() {
        $options = get_option('backtop_options');
        ?>
        <select name="backtop_options[position]">
            <option value="bottom-right" <?php selected($options['position'], 'bottom-right'); ?>>Bottom Right</option>
            <option value="bottom-left" <?php selected($options['position'], 'bottom-left'); ?>>Bottom Left</option>
        </select>
        <?php
    }
    
    function backtop_color_field() {
        $options = get_option('backtop_options');
        ?>
        <input type="color" name="backtop_options[color]" value="<?php echo esc_attr($options['color']); ?>">
        <?php
    }
    
    function backtop_size_field() {
        $options = get_option('backtop_options');
        ?>
        <input type="text" name="backtop_options[size]" value="<?php echo esc_attr($options['size']); ?>" placeholder="e.g., 40px">
        <?php
    }
    
    function backtop_shape_field() {
        $options = get_option('backtop_options');
        ?>
        <select name="backtop_options[shape]">
            <option value="circle" <?php selected($options['shape'], 'circle'); ?>>Circle</option>
            <option value="square" <?php selected($options['shape'], 'square'); ?>>Square</option>
        </select>
        <?php
    }
    
    function backtop_margin_field() {
        $options = get_option('backtop_options');
        ?>
        <input type="text" name="backtop_options[margin]" value="<?php echo esc_attr($options['margin']); ?>" placeholder="e.g., 20px 20px">
        <?php
    }
    
    function backtop_sanitize_options($options) {
        $options['position'] = in_array($options['position'], ['bottom-right', 'bottom-left']) ? $options['position'] : 'bottom-right';
        $options['color'] = sanitize_hex_color($options['color']);
        $options['size'] = preg_match('/^\d+(px|em|%)$/', $options['size']) ? $options['size'] : '40px';
        $options['shape'] = in_array($options['shape'], ['circle', 'square']) ? $options['shape'] : 'circle';
        $options['margin'] = sanitize_text_field($options['margin']);
        return $options;
    }

    JS:

    (function () {
      const backTopTool = document.getElementById("backtop-tool");
      const backTopButton = document.getElementById("backtop");
      const percentageDisplay = document.getElementById("backtop-percentage");
    
      if (backTopTool && backTopButton) {
        const { position, color, size, shape, margin } = backTopOptions || {};
        const [vertical, horizontal] = position.split("-");
        const [marginY, marginX] = margin.split(" ");
        backTopTool.style[vertical] = marginY || "20px";
        backTopTool.style[horizontal] = marginX || "20px";
        backTopButton.style.backgroundColor = color || "#000";
        backTopButton.style.width = size || "40px";
        backTopButton.style.height = size || "40px";
        backTopButton.style.borderRadius = shape === "circle" ? "50%" : "0";
        percentageDisplay.style.fontSize = `${Math.max(parseInt(size) * 0.4, 8)}px`;
      }
    
      const updateScrollProgress = () => {
        const scrollTop = window.scrollY;
        const scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        const scrollPercentage = Math.round((scrollTop / scrollHeight) * 100);
    
        if (percentageDisplay) {
          percentageDisplay.innerHTML = scrollPercentage >= 95 ? "▲" : `${scrollPercentage}%`;
        }
    
        if (backTopButton) {
          backTopButton.classList.toggle("hidden", scrollTop < 200);
        }
      };
    
      const scrollToTop = () => {
        window.scrollTo({ top: 0, behavior: "smooth" });
      };
    
      backTopButton?.addEventListener("click", scrollToTop);
      window.addEventListener("scroll", updateScrollProgress);
    })();

    CSS:

    #backtop-tool {
      position: fixed;
      z-index: 9999;
    }
    
    #backtop-tool ul {
      list-style: none;
      padding: 0;
      margin: 0;
    }
    
    #backtop-tool .hidden {
      display: none;
    }
    
    #backtop-tool li {
      display: flex; 
      justify-content: center; /* 水平居中 */
      align-items: center; /* 垂直居中 */
      width: var(--size, 40px);
      height: var(--size, 40px);
      background: var(--color, rgba(0, 0, 0, 0.7));
      color: #fff;
      border-radius: var(--shape, 50%);
      cursor: pointer;
      font-size: calc(var(--size, 40px) * 0.4); /* 根据按钮大小动态调整字体 */
      text-align: center; /* 对齐数字文本 */
      overflow: hidden;
      box-sizing: border-box;
    }

    管理界面如下:

    从插件制作到实现的过程,给我的感觉是通过插件对页面、功能进行修改,可以避免我们干扰WP核心文件,让页面中的其他功能不受影响,对灵活性、安全性都有一定的增强,这对于我这种半桶水来说非常利好,即便哪里设置错了直接把插件删了就好嘛,可玩性很高。