代码用途:本站Banner随机图片生成

图片来源:Bing搜索引擎每日图片

import os
import shutil
import requests
import random
from PIL import Image
from io import BytesIO
from flask import Flask, send_file, redirect
from datetime import datetime
import threading

app = Flask(__name__)

IMAGE_DIR = 'bing_images'
if not os.path.exists(IMAGE_DIR):
    os.makedirs(IMAGE_DIR)

cropped_images = []
loading_in_progress = False

def get_bing_image_url():
    try:
        url = f'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=8'
        response = requests.get(url)
        data = response.json()
        images_url_dict = data.get('images')
        images_url_list = [(f"https://cn.bing.com{image_dict.get('url')}",image_dict.get('hsh')) for image_dict in images_url_dict]
        return images_url_list
    except Exception as e:
        print(e)
        return None

def crop_image(image_url, filename):
    try:
        img_name = f"{filename}_cropped.jpg"
        img_path = os.path.join(IMAGE_DIR, img_name)
        if not os.path.exists(img_path):
            response = requests.get(image_url)
            img = Image.open(BytesIO(response.content))
            width, height = img.size
            new_height = 800
            new_width = 1920
            left = (width - new_width) / 2
            top = (height - new_height) / 2
            right = (width + new_width) / 2
            bottom = (height + new_height) / 2
            cropped_image = img.crop((left, top, right, bottom))
            img_io = BytesIO()
            cropped_image.save(img_io, 'JPEG')
            img_io.seek(0)
            return img_io
        else:
            return None
    except Exception as e:
        print(e)
        return None

def save_image_to_disk(img_io, filename):
    try:
        img_name = f"{filename}_cropped.jpg"
        img_path = os.path.join(IMAGE_DIR, img_name)
        if not os.path.exists(img_path):
            with open(img_path, 'wb') as img_file:
                shutil.copyfileobj(img_io, img_file)
            cropped_images.append(img_path)
            if len(cropped_images) > 5:
                old_img_path = cropped_images.pop(0)
                os.remove(old_img_path)
            return img_path
    except Exception as e:
        print(e)
        return None

def load_images():
    global loading_in_progress
    loading_in_progress = True
    image_urls = get_bing_image_url()
    if image_urls:
        for item in image_urls:
            cropped_img_io = crop_image(item[0], item[1])
            if cropped_img_io:
                save_image_to_disk(cropped_img_io,item[1])
    loading_in_progress = False

def get_jpg_image_paths(image_dir):
    try:
        jpeg_image_paths = [os.path.join(image_dir, filename) for filename in os.listdir(image_dir) if filename.lower().endswith('.jpg')]
        return jpeg_image_paths
    except Exception as e:
        print(e)
        return []


@app.route('/daily-image', methods=['GET'])
def daily_image():
    current_time = datetime.now().time()
    start_time1 = datetime.strptime("08:00", "%H:%M").time()
    end_time1 = datetime.strptime("09:00", "%H:%M").time()
    start_time2 = datetime.strptime("14:00", "%H:%M").time()
    end_time2 = datetime.strptime("15:00", "%H:%M").time()

    if start_time1 <= current_time <= end_time1 or start_time2 <= current_time <= end_time2 and not loading_in_progress:
        worker = threading.Thread(target=load_images)
        worker.start()

    try:
        if cropped_images:
            img_path = random.choice(cropped_images)
            return send_file(img_path, mimetype='image/jpeg')
        else:
            jpg_images = get_jpg_image_paths(IMAGE_DIR)
            img_path = random.choice(jpg_images)
            return send_file(img_path, mimetype='image/jpeg')
    except Exception as e:
        print(str(e))
        return redirect("http://blueduck.top/wp-content/themes/lolimeow-lolimeow/assets/images/banner/1.jpg")

if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1', port=5000)