【发布时间】:2019-12-21 09:54:03
【问题描述】:
我想创建一个带有图像的按钮网格。每个按钮上的图像都是从一个更大的图像中剪下来的一块 - 所以按钮网格可以看作是原始图像的图块(我用来在按钮上放置图像的代码是from here)。
为了将图像 (image=QPixmap(path_to_image)) 切成小块,我在 for 循环中使用了方法image.copy(x, y, width, height)。
起初我认为代码工作正常。更精确的检查表明图像片段有重叠部分。
这是我用 GIF 图像测试过的代码:
import os
import sys
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtWidgets import \
QWidget, QApplication, \
QGridLayout, \
QLabel, QPushButton
def cut_image_into_tiles(image, rows=4, cols=4) -> dict:
if isinstance(image, str) and os.path.exists(image):
image = QPixmap(image)
elif not isinstance(image, QPixmap):
raise ValueError("image must be str or QPixmap object")
# Dim of the tile
tw = int(image.size().width() / cols)
th = int(image.size().height() / rows)
# prepare return value
tiles = {"width": tw, "height": th}
for r in range(rows):
for c in range(cols):
tile = image.copy(c * th, r * tw, tw, th)
# args: x, y, width, height
# https://doc.qt.io/qt-5/qpixmap.html#copy-1
tiles[(r, c)] = tile
return tiles
def create_pixmapbutton(pixmap, width=0, height=0) -> QPushButton:
if isinstance(pixmap, QPixmap):
button = QPushButton()
if width > 0 and height > 0:
button.setIconSize(QSize(width, height))
else:
button.setIconSize(pixmap.size())
button.setIcon(QIcon(pixmap))
return button
def run_viewer(imagepath, rows=4, cols=4):
# ImageCutter.run_viewer(imagepath)
app = QApplication(sys.argv)
image = QPixmap(imagepath)
tiles = cut_image_into_tiles(image=image, rows=rows, cols=cols)
tilewidth = tiles["width"]
tileheight = tiles["height"]
# get dict tiles (keys:=(row, col) or width or height)
viewer = QWidget()
layout = QGridLayout()
viewer.setLayout(layout)
viewer.setWindowTitle("ImageCutter Viewer")
lbl = QLabel()
lbl.setPixmap(image)
layout.addWidget(lbl, 0, 0, rows, cols)
for r in range(rows):
for c in range(cols):
btn = create_pixmapbutton(
tiles[r, c], width=tilewidth, height=tileheight)
btninfo = "buttonsize={}x{}".format(tilewidth, tileheight)
btn.setToolTip(btninfo)
# logger.debug(" create button [{}]".format(btninfo))
layout.addWidget(btn, r, cols + c)
viewer.show()
sys.exit(app.exec_())
我用run_viewer(path_to_a_gif_image, rows=3, cols=3)测试了代码
【问题讨论】:
-
imagepath的大小是多少? -
imagepath 只是 gif 文件的路径还是你的意思是 gif 的大小?
-
是的,分享 gif
-
如何分享 gif?
-
上传到drive、dropbox、imgur等并分享链接。
标签: python image pyqt5 qpixmap