XPrintServer/XPrint.Image/TiffModifier.cs
2025-11-16 19:33:01 +08:00

71 lines
2.1 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using BitMiracle.LibTiff.Classic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace XPrint.Image
{
// 定义通道名称映射类
[XmlRoot("ChannelNames")]
public class ChannelNameMapping
{
[XmlElement("Channel")]
public List<Channel> Channels { get; set; } = null!;
}
public class Channel
{
[XmlAttribute("Index")]
public int Index { get; set; }
[XmlAttribute("Name")]
public string Name { get; set; } = null!;
}
public class TiffModifier
{
public static void RenameCustomChannels(string inputPath, string outputPath, Dictionary<int, string> channelNames)
{
using (Tiff tiff = Tiff.Open(inputPath, "r+"))
{
if (tiff == null) throw new IOException("无法打开TIFF文件");
// 遍历所有IFD修改首IFD的ImageDescription标签
tiff.SetDirectory(0); // 仅修改首IFD的元数据
var xmlSerializer = new XmlSerializer(typeof(ChannelNameMapping));
tiff.ReadEXIFDirectory(0);
// 构建XML元数据
var mapping = new ChannelNameMapping
{
Channels = new List<Channel>()
};
foreach (var kvp in channelNames)
{
mapping.Channels.Add(new Channel { Index = kvp.Key, Name = kvp.Value });
}
using (StringWriter writer = new StringWriter())
{
xmlSerializer.Serialize(writer, mapping);
string xmlData = writer.ToString();
// 写入ImageDescription标签0x010E
tiff.SetField(TiffTag.IMAGEDESCRIPTION, xmlData);
}
// 保存修改
tiff.WriteDirectory();
}
// 覆盖原文件
File.Copy(inputPath, outputPath, true);
}
}
}