图像

Full-Stack-python / 2023-08-27 / 原文

图像对于使您的应用更有趣非常重要。

在 NodeGui 中,QLabel 通常用于显示文本,但它也可以显示图像。

一个非常小的例子如下所示:

const { QMainWindow, QPixmap, QLabel } = require('@nodegui/nodegui');

const win = new QMainWindow();
const label = new QLabel();

const absoulteImagePath = '/Users/atulr/Project/nodegui/nodegui/extras/assets/logox200.png';
const image = new QPixmap();
image.load(absoulteImagePath);

label.setPixmap(image);

win.setCentralWidget(label);
win.show();
global.win = win;

这里

  • 我们首先使用 QLabel 创建一个标签。
  • 然后我们创建一个 QPixmap 的实例。 用于表示内存中的图像。QPixmap不是小部件,因此无法按原样显示在屏幕上。QPixmap
  • 因此,我们使用 QLabel 实例并为其设置 QPixmap。

使用 url 加载图像#

假设我们想从互联网上的 URL 加载图像。在这种情况下,我们不能使用 QPixmap 的方法,因为它只保留给本地文件系统映像。load()

相反,我们将使用 axios 作为缓冲区下载图像,并使用 QPixmap 的方法 loadFromData。

因此,让我们从 axios 安装开始:

npm i axios

现在让我们创建一个函数,该函数将 URL 作为参数,并将为 GIF 返回已配置的 QMovie 实例:

const axios = require('axios');

async function getPixmap(url) {
    const { data } = await axios.get(url, { responseType: 'arraybuffer' });
    const pixmap = new QPixmap();
    pixmap.loadFromData(data);
    return pixmap;
}

该函数接收一个 URL,告诉 axios 将图像下载为缓冲区,然后使用该缓冲区创建 QPixmap 实例。getPixmap

由于getPixmap返回了一个承诺,我们需要对代码进行一些更改。经过一些小的重构后,我们最终得到以下内容。

const { QMainWindow, QPixmap, QLabel } = require('@nodegui/nodegui');
const axios = require('axios');
async function getPixmap(url) {
    const { data } = await axios.get(url, { responseType: 'arraybuffer' });
    const pixmap = new QPixmap();
    pixmap.loadFromData(data);
    return pixmap;
}
async function main() {
    const win = new QMainWindow();
    const label = new QLabel();
    const image = await getPixmap('https://upload.wikimedia.org/wikipedia/commons/9/96/Nature-morocco.jpg');
    label.setPixmap(image);
    win.setCentralWidget(label);
    win.show();
    global.win = win;
}
main().catch(console.error);

一些提示#

显示大图像#

上面的示例不允许您在不剪切或使小部件变大的情况下显示巨大的图像。

为此:

  • 您可以使用 QPixmap 创建镜像实例
  • 将镜像实例设置为 QLabel
  • 最后将QLabel设置为QScrollArea,如果图像太大,则允许您滚动图像。

动画图像#

为了使用动画图像

  • 代替QPixmap使用QMovie
  • 而不是标签的方法使用setPixmapsetMovie

更多细节可以在这篇博文中看到:https://www.sitepoint.com/build-native-desktop-gif-searcher-app-using-nodegui/