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) { struct heif_context* ctx = heif_context_alloc(); if (!ctx) { throw std::runtime_error("Failed to allocate HEIF context."); }
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); memcpy(buffer.data(), data, buffer.size());
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(); }
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; } }
|