Не могу открыть результирующую картинку. Я ее записую в функции get_image(все происходит без ошибок, но почему то она не декодируется)
BASE_URL = 'https://pixabay.com/api/'
API_KEY = '16480353-7dbad8920b220c290462d5818'
PER_PAGE = 3
counter = 0
def __init__(self, titles, signal):
QThread.__init__(self)
self.titles = titles
self.signal = signal
def get_image(self, title):
response = requests.get(f'{GetImagesThread.BASE_URL}?key={GetImagesThread.API_KEY}&q={title}&per_page={GetImagesThread.PER_PAGE}')
if response.status_code == 200:
url = json.loads(response.content.decode('utf-8'))['hits'][0]['previewURL']
print(url)
image_response = requests.get(url, stream=True)
print(image_response.content)
if image_response.status_code == 200:
photo_label = QLabel()
with open(f"./temp/img{GetImagesThread.counter}.{url[-3:]}", 'wb') as f:
image_response.raw.decode_content = True
shutil.copyfileobj(image_response.raw, f)
pixmap = QPixmap(f"./temp/img{GetImagesThread.counter}.{url[-3:]}")
photo_label.setPixmap(pixmap)
GetImagesThread.counter += 1
return photo_label
def run(self):
for title in self.titles:
image = self.get_image(title)
try:
self.signal.emit(image)
except Exception as err:
print(err)
class Window(QMainWindow):
add_image = pyqtSignal(QLabel)
def __init__(self):
super().__init__()
self.title = 'Pixabay'
self.init_window()
self.init_ui()
self.show()
def init_window(self):
self.setWindowTitle(self.title)
self.setGeometry(150, 150, 600, 400)
def init_ui(self):
root_layout = QVBoxLayout()
input_layout = QHBoxLayout()
self.images_layout = QVBoxLayout()
input_layout.setAlignment(Qt.AlignTop)
self.titles_input = QLineEdit()
self.titles_input.setPlaceholderText('Enter the titles')
input_layout.addWidget(self.titles_input)
get_images_button = QPushButton('Get images')
get_images_button.clicked.connect(self.get_images)
input_layout.addWidget(get_images_button)
root_layout.addLayout(input_layout)
self.loader = QProgressBar()
root_layout.addWidget(self.loader)
root_layout.addLayout(self.images_layout)
root_widget = QWidget()
root_widget.setLayout(root_layout)
self.setCentralWidget(root_widget)
def get_images(self):
titles_list = str(self.titles_input.text()).split(',')
self.loader.setMaximum(len(titles_list))
self.loader.setValue(0)
self.thread = GetImagesThread(titles_list, self.add_image)
self.add_image.connect(self.add_image_label)
self.thread.start()
def add_image_label(self, image_label):
self.loader.setValue(self.loader.value() + 1)
Ответы (1 шт):
Автор решения: D. Violet
→ Ссылка
Я проверил Ваш код, благо в нём есть API ключ.
Файл картинки создаётся с нулевым размером.
вы можете использовать
if image_response.status_code == 200:
with open(f'img{counter}.{url[-3:]}', 'wb') as f:
f.write(image_response.content)
для сохранения картинки, вместо shutil.copyfileobj(image_response.raw, f)