facebook-tool/services/image_service.py

49 lines
1.4 KiB
Python

# services/image_service.py
import os
import requests
from PyQt6.QtGui import QPixmap
from PyQt6.QtCore import Qt
class ImageService:
@staticmethod
def get_display_pixmap(image_path_or_url, size=60):
"""
Load image from local path or URL and return QPixmap scaled.
Returns None if cannot load.
"""
pixmap = QPixmap()
if not image_path_or_url:
return None
# Local file
if os.path.exists(image_path_or_url):
pixmap.load(image_path_or_url)
# URL
elif image_path_or_url.startswith("http"):
try:
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
resp = requests.get(image_path_or_url, headers=headers)
if resp.status_code == 200:
pixmap.loadFromData(resp.content)
else:
return None
except Exception as e:
print("Failed to load image from URL:", e)
return None
else:
return None
if not pixmap.isNull():
# PyQt6: enum cần gọi qua Qt.AspectRatioMode và Qt.TransformationMode
pixmap = pixmap.scaled(
size,
size,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
return pixmap
return None