C/C++

使用exiv2读取或者修改图片元数据

0. 前言

开发环境为Windows,使用vcpkg安装exiv2库。关于vcpkg的安装,请参考vcpkg官方文档。 如果使用其他环境,请自行通过搜索引擎查找相关资料。

1. 安装 exiv2

vcpkg install exiv2

2. CMmakeLists.txt 配置

include("C:\\vcpkg\\scripts\\buildsystems\\vcpkg.cmake") # 此处修改为你的vcpkg安装路径
find_package(exiv2 CONFIG REQUIRED)
target_link_libraries(your_target PRIVATE Exiv2::exiv2lib) # 此处的your_target请修改为你的项目名称

3. 引入头文件

#include <exiv2/exiv2.hpp>

4. 读取图片元数据

static Exiv2::ExifData::const_iterator GetExifValue(Exiv2::ExifData& ed, const std::string& key) {
	Exiv2::ExifKey tmp = Exiv2::ExifKey(key);
	Exiv2::ExifData::iterator tag = ed.findKey(tmp);
	return tag;
}

5. 修改图片元数据

static bool SetExifValue(Exiv2::ExifData& ed, const std::string& key, const std::string& value) {
	Exiv2::ExifKey tmp = Exiv2::ExifKey(key);
	Exiv2::ExifData::iterator tag = ed.findKey(tmp);
	if (tag != ed.end()) {
		return tag->setValue(value) == 0;
	}
	return false;
}

6. 完整代码

#include <exiv2/exiv2.hpp>
#include <iostream>


// 获取exif数据
static Exiv2::ExifData::const_iterator GetExifValue(Exiv2::ExifData& ed, const std::string& key) {
	Exiv2::ExifKey tmp = Exiv2::ExifKey(key);
	Exiv2::ExifData::iterator tag = ed.findKey(tmp);
	return tag;
}

// 修改exif数据
static bool SetExifValue(Exiv2::ExifData& ed, const std::string& key, const std::string& value) {
	Exiv2::ExifKey tmp = Exiv2::ExifKey(key);
	Exiv2::ExifData::iterator tag = ed.findKey(tmp);
	if (tag != ed.end()) {
		return tag->setValue(value) == 0;
	}
	return false;
}

int main() {
	try {
		// 打开图片文件
		std::string imagePath = "E:\\Projects\\Demo\\test.JPG";  // Replace with the actual image path
		std::unique_ptr<Exiv2::Image> image = Exiv2::ImageFactory::open(imagePath);

		if (image.get() == 0) {
			std::cerr << "Failed to open the image" << std::endl;
			return EXIT_FAILURE;
		}


		// 获取exif数据
		image->readMetadata();
		Exiv2::ExifData& exifData = image->exifData();

		// 修改exif数据
		bool result = SetExifValue(exifData, "Exif.Image.Make", "Demo");
		if (result) {
			// 保存修改
			image->setExifData(exifData);
			image->writeMetadata();
		}
		else {
			std::cout << "Failed to modify Exif.Image.Make" << std::endl;
		}

		// 遍历exif数据,打印所有的key和value
		for (Exiv2::ExifData::const_iterator it = exifData.begin(); it != exifData.end(); ++it) {
			std::cout << it->key() << " : " << it->value() << std::endl;
		}
	}
	catch (Exiv2::Error& ex) {
		std::cerr << "Caught Exiv2 exception: " << ex << std::endl;
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
最近的文章

React深入理解

更早的文章

Typescript装饰器简介(下)

欢迎在评论区留下您的见解~