标签: Python

  • 【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()
  • 【Python】对本地网页进行元素提取并输出Excel

    一些网页通过加载Js来保护页面元素,当我们突破Js得到本地页面时,可以使用BS4库对页面进行分析,提取对应的元素来综合有价值的内容。

    示例代码:

    import requests
    from bs4 import BeautifulSoup
    import pandas as pd
    
    # 发送请求并获取网页内容
    url = 'your_local_or_online_page_url'
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 定义一个空的列表来存储提取的数据
    data = []
    
    # 遍历页面中的项目列表,假设项目数据都在某个父元素中
    projects = soup.find_all('tr', class_='project-id')  # 根据实际情况修改选择器
    
    # 提取每个项目的各项数据
    for project in projects:
        # 获取项目ID
        project_id = project.find('td', class_='project-id-class').get_text(strip=True)  # 修改为实际选择器
        
        # 将提取的数据添加到列表中
        data.append([project_id]) # 按实际修改
    
    # 创建 DataFrame 并保存为 Excel
    df = pd.DataFrame(data, columns=['ID']) # 按实际修改
    df.to_excel('projects_data.xlsx', index=False)
    
    print("Data has been successfully extracted and saved to 'projects_data.xlsx'.")

    主要用到了BS4库。

    示意代码:

    from bs4 import BeautifulSoup
    
    # 假设有一个HTML文档
    html_doc = """
    <html>
      <head><title>Example Page</title></head>
      <body>
        <p class="title"><b>Sample Page</b></p>
        <p class="story">This is a test story. <a href="http://example.com/1" class="link">link1</a> <a href="http://example.com/2" class="link">link2</a></p>
        <p class="story">Another test story.</p>
      </body>
    </html>
    """
    
    # 使用 BeautifulSoup 解析 HTML 文档
    soup = BeautifulSoup(html_doc, 'html.parser')
    
    # 提取<title>标签的内容
    title = soup.title.string
    print(f"Title: {title}")
    
    # 提取所有的链接(<a> 标签)
    links = soup.find_all('a')
    for link in links:
        print(f"Link text: {link.string}, URL: {link['href']}")
    
    # 查找特定类的<p>标签
    story_paragraphs = soup.find_all('p', class_='story')
    for p in story_paragraphs:
        print(f"Story paragraph: {p.get_text()}")

  • 【Python】裁切图片为指定画幅比例

    该工具是在截取MTV的画面时产生的需求,一些4:3画幅的视频制作时候加入了黑边,成了16:9视频,因此想截图出原本4:3的画面,一方面可以进剪辑软件进行直接裁剪,也可以在原视频进行导出后操作,考虑到二压费时费力,因此选择对截取的图片进行批处理。

    import os
    import random
    import string
    from tkinter import Tk, filedialog, Button, Label, messagebox
    from PIL import Image
    
    
    def random_filename(extension):
        """生成随机文件名"""
        chars = string.ascii_letters + string.digits
        return ''.join(random.choices(chars, k=8)) + f".{extension}"
    
    
    def crop_to_aspect(image, target_ratio=4/3):
        """裁剪图像宽边以符合指定宽高比"""
        width, height = image.size
        current_ratio = width / height
    
        if current_ratio > target_ratio:  # 如果宽高比大于目标比例,宽度过大
            new_width = int(height * target_ratio)  # 计算符合比例的新宽度
            left = (width - new_width) // 2  # 左侧裁剪量
            right = left + new_width  # 右侧裁剪量
            image = image.crop((left, 0, right, height))  # 裁剪左右宽边
    
        return image
    
    
    def process_images():
        """处理图片并保存结果"""
        input_files = filedialog.askopenfilenames(
            title="选择图片文件",
            filetypes=[("Image Files", "*.jpg *.png")]
        )
        if not input_files:
            return
    
        output_dir = filedialog.askdirectory(title="选择输出文件夹")
        if not output_dir:
            return
    
        for file_path in input_files:
            try:
                with Image.open(file_path) as img:
                    # 转换为符合比例的图片
                    processed_img = crop_to_aspect(img)
                    # 保存文件
                    ext = file_path.split('.')[-1]
                    output_path = os.path.join(output_dir, random_filename(ext))
                    processed_img.save(output_path)
            except Exception as e:
                messagebox.showerror("错误", f"处理文件 {file_path} 时出错: {e}")
                continue
    
        messagebox.showinfo("完成", "图片批量处理完成!")
    
    
    def create_gui():
        """创建GUI"""
        root = Tk()
        root.title("图片批量处理工具")
        root.geometry("400x200")
    
        Label(root, text="批量处理图片 - 保持高度裁切宽边为4:3比例").pack(pady=20)
        Button(root, text="选择图片并处理", command=process_images).pack(pady=10)
        Button(root, text="退出", command=root.quit).pack(pady=10)
    
        root.mainloop()
    
    
    if __name__ == "__main__":
        create_gui()