Exiv2 —— 增加/修改图片Exif信息(附源码)

效果Exiv2 —— 增加/修改图片Exif信息(附源码)_第1张图片

源码
int main()
{
	// 方式1加入键值对
	Exiv2::ExifData exifData;
	exifData["Exif.Image.Model"] = "Test 1";                     // AsciiValue
	exifData["Exif.Image.SamplesPerPixel"] = uint16_t(162);      // UShortValue
	exifData["Exif.Image.XResolution"] = int32_t(-2);            // LongValue
	exifData["Exif.Image.YResolution"] = Exiv2::Rational(-2, 3); // RationalValue
	exifData["Exif.GPSInfo.GPSLongitude"] = Exiv2::Rational(50,20);; // RationalValue
	std::cout << "Added a few tags the quick way.\n";

	// 方式2加入键值对
	Exiv2::Value::AutoPtr v = Exiv2::Value::create(Exiv2::asciiString);
	v->read("1999:12:31 23:59:59");
	Exiv2::ExifKey key("Exif.Photo.DateTimeOriginal");
	exifData.add(key, v.get());
	std::cout << "Added key \"" << key << "\", value \"" << *v << "\"\n";

	// 方式3加入键值对
	Exiv2::URationalValue::AutoPtr rv(new Exiv2::URationalValue);
	rv->read("1/2 1/3");
	// 通过rational value的扩展接口添加更多元素
	rv->value_.push_back(std::make_pair(2, 3));
	rv->value_.push_back(std::make_pair(3, 4));
	// 将键值对添加到Exif数据
	key = Exiv2::ExifKey("Exif.Image.PrimaryChromaticities");
	exifData.add(key, rv.get());
	std::cout << "Added key \"" << key << "\", value \"" << *rv << "\"\n";

	// 方式4加入键值对
	// 既然我们知道元数据存在(或者如果不存在,我们不介意创建新标签),我们可以简单地这样做
	Exiv2::Exifdatum& tag = exifData["Exif.Photo.DateTimeOriginal"];
	std::string date = tag.toString();
	date.replace(0, 4, "2000");
	tag.setValue(date);
	std::cout << "Modified key \"" << tag.key() << "\", new value \"" << tag.value() << "\"\n";

	// 方式5加入键值对
	// 或者,我们可以使用findKey()
	key = Exiv2::ExifKey("Exif.Image.PrimaryChromaticities");
	Exiv2::ExifData::iterator pos = exifData.findKey(key);
	if (pos != exifData.end())
	{
		// 获取指向值副本的指针
		v = pos->getValue();
		// 将值指针向下投射到其实际类型
		Exiv2::URationalValue* prv = dynamic_cast<Exiv2::URationalValue*>(v.release());
		if (prv != 0)
		{
			rv = Exiv2::URationalValue::AutoPtr(prv);
			// 通过URationalValue接口直接修改值
			rv->value_[2] = std::make_pair(88, 77);
			// 将修改后的值复制回元基准
			pos->setValue(rv.get());
			std::cout << "Modified key \"" << key << "\", new value \"" << pos->value() << "\"\n";
		}
		else { std::cout << "Downcast failed"; }
	}
	else { std::cout << "Key not found"; }

	 // 最后,将剩余的Exif数据写入图像文件
	const char imagePath[] = "./test.jpeg";
	Exiv2::Image::AutoPtr image = Exiv2::ImageFactory::open(imagePath);
	assert(image.get() != 0);
	image->setExifData(exifData);
	image->writeMetadata();

	system("pause");
	return 0;
}

关注

笔者 - jxd

你可能感兴趣的:(Exiv2,c++,exif,jpeg,exiv2)