首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C#中将EXIF数据写入图像?

在C#中将EXIF数据写入图像可以通过使用System.Drawing.Imaging命名空间中的类来实现。以下是一个示例代码,演示了如何将EXIF数据写入图像:

代码语言:txt
复制
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

public class ExifWriter
{
    public static void WriteExifData(string imagePath, string key, string value)
    {
        using (Image image = Image.FromFile(imagePath))
        {
            PropertyItem[] propertyItems = image.PropertyItems;

            // 创建一个新的PropertyItem对象
            PropertyItem newItem = (PropertyItem)Activator.CreateInstance(typeof(PropertyItem));

            // 设置PropertyItem的ID
            newItem.Id = 0x9003; // 0x9003表示Image Description

            // 设置PropertyItem的类型为ASCII字符串
            newItem.Type = 2;

            // 设置PropertyItem的值为ASCII字符串的字节数组
            newItem.Value = Encoding.ASCII.GetBytes(value + '\0');

            // 设置PropertyItem的长度
            newItem.Len = newItem.Value.Length;

            // 将新的PropertyItem添加到PropertyItem数组中
            Array.Resize(ref propertyItems, propertyItems.Length + 1);
            propertyItems[propertyItems.Length - 1] = newItem;

            // 将修改后的PropertyItems数组重新设置给图像
            image.SetPropertyItem(newItem);

            // 保存修改后的图像
            image.Save(imagePath);
        }
    }
}

使用上述代码,你可以通过调用WriteExifData方法来将EXIF数据写入图像。其中,imagePath参数表示图像文件的路径,key参数表示EXIF数据的键,value参数表示EXIF数据的值。

以下是一个示例调用代码:

代码语言:txt
复制
string imagePath = "path/to/image.jpg";
string key = "ImageDescription";
string value = "This is a sample image.";

ExifWriter.WriteExifData(imagePath, key, value);

这个示例代码将在指定的图像文件中添加一个名为"ImageDescription"的EXIF数据,并将其值设置为"This is a sample image."。

请注意,这只是一个简单的示例,你可以根据需要修改和扩展代码来处理其他类型的EXIF数据。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券