gpt4 book ai didi

c++ - 将 QImage 转换为 char*

转载 作者:行者123 更新时间:2023-11-30 05:03:33 25 4
gpt4 key购买 nike

我捕获图像并使用 QByteArray 在其中存储和保存图像:

QImage image(WEB_SCREENSHOT_WIDTH, page.viewportSize().height()/*65000,*/, QImage::Format_ARGB32_Premultiplied);
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG");

我想将 QByteArray 传递给 char* 并在函数末尾返回它,如下所示:

unsigned char* char_return = (unsigned char*)bytes.data();  

我必须这样做,因为我的程序的其余部分是基于 C 的...
但是最后保存的文件打不开
请帮助我

编辑:
最小的功能是这样的:

unsigned char* web_screenshot::get_web_image(){
QImage image(WEB_SCREENSHOT_WIDTH, page.viewportSize().height(), QImage::Format_ARGB32_Premultiplied);
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG");
unsigned char* char_return = (unsigned char*)bytes.data();
return char_return;
}

最佳答案

像这样对 bytes.data() 进行深拷贝:

unsigned char *data = (unsigned char *) malloc unsigned char(bytes.size());
memcpy(data, reinterpret_cast<unsigned char *>(bytes.data()), bytes.size());

更新:

下面,您可以看到一个功能示例,其中原始图像数据的拷贝用于加载显示在 UI 上的新图像:

unsigned char* deepCopyImageData(int &size){
QImage image("test.png"); // test image
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG");
buffer.close();

unsigned char *data = (unsigned char *) malloc(bytes.size());
memcpy(data, reinterpret_cast<unsigned char *>(bytes.data()), bytes.size());
size = bytes.size();
return data;
}

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

int size;
unsigned char *data = deepCopyImageData(size);

QImage image;
if(!image.loadFromData(data,size))
qWarning("Image loading failed");

free(data); data = nullptr;
QLabel *label = new QLabel();
label->setPixmap(QPixmap::fromImage(image));
label->show();

return a.exec();
}

关于c++ - 将 QImage 转换为 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49358779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com