Download Images from Pixabay using Python

šŸ“ø Download Images from Pixabay using Python

Want to download high-quality images automatically from Pixabay using Python? This project helps you fetch images from Pixabay based on any keyword, using the official Pixabay API. It’s perfect for building datasets, wallpapers, or AI training image collections easily!

🧩 Step 1: Install Required Module

This script uses two simple Python modules:

  • requests — to make API calls and download images.
  • tqdm — to show a progress bar while downloading.

Install them using pip:

pip install requests tqdm

šŸš€ Step 2: Get Your Pixabay API Key

You’ll need a free API key from Pixabay to access their image API. Visit Pixabay API Docs and create an account to get your key. Once you have it, replace the placeholder in the code below with your API key.

šŸ’» Step 3: Write the Python Script

Create a new file, for example pixabay_downloader.py, and paste the following code:


# Code By : Atul Kushwaha || Chat GPT
import os
import requests
from tqdm import tqdm

# Pixabay API Key (Replace with your valid key)
API_KEY = 'YOUR_PIXABAY_API_KEY'

# Configuration
SEARCH_QUERY = "Nature"   # Change this to any topic you like
TOTAL_IMAGES = 3          # Number of images to fetch

# Orientation options
ORIENTATION = 'landscape'   # Common choice
# ORIENTATION = 'portrait'
# ORIENTATION = 'all'

# Folder to save images
SAVE_FOLDER = "output"
os.makedirs(SAVE_FOLDER, exist_ok=True)

# Pixabay API URL
url = (
    f'https://pixabay.com/api/?key={API_KEY}'
    f'&q={SEARCH_QUERY}&image_type=photo&orientation={ORIENTATION}'
    f'&per_page={TOTAL_IMAGES}&safesearch=true'
)

# Fetch and download images
response = requests.get(url)
if response.status_code == 200:
    data = response.json()

    if not data['hits']:
        print("⚠️ No images found for your search.")
    else:
        print(f"\nšŸ” Found {len(data['hits'])} images for '{SEARCH_QUERY}' ({ORIENTATION}). Downloading...\n")
        for i, hit in enumerate(tqdm(data['hits'], desc=f'Downloading {SEARCH_QUERY}')):
            image_url = hit.get('largeImageURL')
            if not image_url:
                continue

            file_name = os.path.join(SAVE_FOLDER, f'{SEARCH_QUERY.replace(' ', '_').lower()}_{i+1}.jpg')
            try:
                image_data = requests.get(image_url).content
                with open(file_name, 'wb') as f:
                    f.write(image_data)
            except Exception as e:
                print(f"❌ Failed to download image {i+1}: {e}")

        print(f"\n✅ Successfully downloaded {len(data['hits'])} images for '{SEARCH_QUERY}'.")
else:
    print(f"❌ Error: {response.status_code}")

print("\nšŸŽ‰ Download complete.")

⚙️ Step 4: Run the Script

Save the file and run it in your terminal:

python pixabay_downloader.py

The script will automatically create an output folder and save the downloaded images there. You can change the topic, number of images, or orientation easily.

🧠 How It Works

  • The script sends a request to the Pixabay API with your search query.
  • It parses the response and extracts image URLs.
  • Each image is downloaded and saved locally using requests.
  • The tqdm library shows download progress in the terminal.

šŸ’” Use Cases

  • Building custom image datasets for AI or ML models.
  • Creating automated wallpaper downloaders.
  • Gathering stock photos for projects or blogs.

šŸŽÆ Project Summary

  • Language: Python
  • Libraries Used: requests, tqdm
  • API: Pixabay Image API
  • Output: Folder with downloaded images

šŸ“¢ Stay Connected

❤️ If you found this helpful, share it with your friends and help more developers explore Python automation!

Previous Post Next Post

Contact Form