Qt使用libheif库显示苹果的heic图片

Qt使用libheif库显示苹果的heic图片

1.先使用vcpkg安装libheif库

自己根据需要选择位数以及动态库还是静态库

1
2
vcpkg install libheif:x86-windows-static
vcpkg install libheif:x64-windows-static

2.直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <QApplication>
#include <QLabel>
#include <QImage>
#include <QPixmap>
#include <libheif/heif.h>
#include <iostream>

QImage heifToQImage(const std::string& filePath) {
// 初始化 libheif 句柄
struct heif_context* ctx = heif_context_alloc();
if (!ctx) {
throw std::runtime_error("Failed to allocate HEIF context.");
}

// 读取 HEIF 文件
struct heif_error err = heif_context_read_from_file(ctx, filePath.c_str(), nullptr);
if (err.code != heif_error_Ok) {
heif_context_free(ctx);
throw std::runtime_error("Failed to read HEIF file: " + std::string(err.message));
}

// 获取主图像句柄
struct heif_image_handle* handle = nullptr;
err = heif_context_get_primary_image_handle(ctx, &handle);
if (err.code != heif_error_Ok) {
heif_context_free(ctx);
throw std::runtime_error("Failed to get primary image handle: " + std::string(err.message));
}

// 解码图像
struct heif_image* img = nullptr;
err = heif_decode_image(handle, &img, heif_colorspace_RGB, heif_chroma_interleaved_RGBA, nullptr);
if (err.code != heif_error_Ok) {
heif_image_handle_release(handle);
heif_context_free(ctx);
throw std::runtime_error("Failed to decode HEIF image: " + std::string(err.message));
}

// 获取图像数据
int width = heif_image_get_width(img, heif_channel_interleaved);
int height = heif_image_get_height(img, heif_channel_interleaved);
const uint8_t* data = heif_image_get_plane_readonly(img, heif_channel_interleaved, nullptr);

// 创建缓冲区并复制数据
QVector<uchar> buffer(width * height * 4); // RGBA8888,每像素4字节
memcpy(buffer.data(), data, buffer.size());

// 转换为 QImage
QImage qimage(buffer.data(), width, height, QImage::Format_RGBA8888);

// 释放资源
heif_image_release(img);
heif_image_handle_release(handle);
heif_context_free(ctx);

return qimage.copy(); // 确保 QImage 独立持有数据
}


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

try {
QImage image = heifToQImage("C:/Users/lianx/Pictures/IMG_0001.HEIC");

QLabel label;
label.setPixmap(QPixmap::fromImage(image));
label.setScaledContents(true);
label.resize(image.size()/2);
label.show();

return app.exec();
}
catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return -1;
}
}

3.效果如图