You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python批量下载TXT文件中URL图片至指定路径并统一调整为256x256尺寸的技术需求问询

Alright, let's walk through how to solve this exactly as you need it. I'll break down the solution into easy-to-follow parts with code and clear explanations.

Solution: Download & Resize Images from URL List

First, you'll need two key Python libraries to pull this off: requests for downloading images, and Pillow (the modern PIL fork) for resizing. Install them first if you haven't:

pip install requests pillow

Below is the complete script, followed by a breakdown of how each part works:

import os
import requests
from PIL import Image
from urllib.parse import urlparse

def download_image(url, save_path):
    """Download an image from a URL and save it to the specified folder"""
    try:
        # Stream the request to handle large images efficiently
        response = requests.get(url, stream=True)
        response.raise_for_status()  # Throw an error for HTTP issues (e.g., 404, 500)
        
        # Extract filename from the URL, or use a fallback if extraction fails
        parsed_url = urlparse(url)
        filename = os.path.basename(parsed_url.path)
        if not filename:
            # Use a hash of the URL to create a unique filename (avoids overwrites)
            filename = f"image_{hash(url)}.jpg"
        
        full_save_path = os.path.join(save_path, filename)
        
        # Save the image in chunks
        with open(full_save_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        return full_save_path
    except Exception as e:
        print(f"Failed to download {url}: {str(e)}")
        return None

def resize_image(image_path, target_size=(256, 256)):
    """Resize an image to the exact 256x256 resolution"""
    try:
        with Image.open(image_path) as img:
            # Use LANCZOS resampling for high-quality scaling (best for up/down sizing)
            resized_img = img.resize(target_size, Image.Resampling.LANCZOS)
            # Overwrite the original downloaded image with the resized version
            resized_img.save(image_path)
            print(f"Successfully resized: {image_path}")
    except Exception as e:
        print(f"Failed to resize {image_path}: {str(e)}")

def main():
    # Update these paths to match your setup
    url_file = "your_url_list.txt"  # Path to your TXT file with URLs
    save_folder = r"C:\Users\username\Pictures"  # Replace 'username' with your actual Windows username
    
    # Ensure the save folder exists (create it if not)
    os.makedirs(save_folder, exist_ok=True)
    
    # Read URLs from the TXT file (space-separated on one line)
    try:
        with open(url_file, 'r') as f:
            url_content = f.read().strip()
            url_list = url_content.split()  # Split by spaces to get individual URLs
        
        print(f"Found {len(url_list)} URLs to process...")
        
        # Process each URL one by one
        for url in url_list:
            print(f"Working on: {url}")
            downloaded_image = download_image(url, save_folder)
            if downloaded_image:
                resize_image(downloaded_image)
    
    except Exception as e:
        print(f"Error reading URL file: {str(e)}")

if __name__ == "__main__":
    main()

Key Details & Notes:

  • Filename Handling: The script tries to keep the original filename from the URL. If that's not possible (e.g., the URL has no clear filename), it creates a unique name using a hash of the URL to prevent overwriting existing images.
  • High-Quality Resizing: We use Image.Resampling.LANCZOS (available in Pillow 9.1.0+) because it produces the sharpest results for both downscaling and upscaling images. If you need to preserve the original aspect ratio (instead of forcing exact 256x256), just let me know—I can adjust the code to add padding instead of stretching.
  • Error Resilience: Each step includes error handling to catch broken URLs, network issues, or invalid image files. The script will skip problematic entries and keep processing the rest.
  • Path Setup: Don't forget to update url_file to point to your actual TXT file, and replace username in the save_folder path with your Windows username.

Quick Usage Steps:

  1. Install the required libraries with the pip command above.
  2. Update the path variables in the script to match your files and folder.
  3. Add your space-separated URLs to the TXT file (e.g., https://example.com/img1.jpg https://example.com/img2.png).
  4. Run the script—it will download every image, resize it to 256x256, and save everything to your Pictures folder.

内容的提问来源于stack exchange,提问作者Vishal Reddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 09:23:15