48 lines
1.7 KiB
C#
48 lines
1.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace XPrint.Image
|
|
{
|
|
public class PSDModifier
|
|
{
|
|
private const int HeaderSize = 26;
|
|
private const int ChannelInfoOffset = 128; // 通道信息起始偏移量(需根据实际文件调整)
|
|
|
|
public static void RenameChannel(string filePath, string oldName, string newName)
|
|
{
|
|
byte[] fileData = File.ReadAllBytes(filePath);
|
|
|
|
// 1. 验证 PSD 文件头
|
|
if (Encoding.ASCII.GetString(fileData, 0, 4) != "8BPS")
|
|
throw new InvalidDataException("非有效 PSD 文件");
|
|
|
|
// 2. 定位通道信息块
|
|
int channelCount = fileData[12]; // 第 13 字节为通道数
|
|
int infoOffset = BitConverter.ToInt32(fileData, HeaderSize + 4); // 通道信息块偏移量
|
|
|
|
// 3. 遍历通道信息
|
|
for (int i = 0; i < channelCount; i++)
|
|
{
|
|
int channelOffset = infoOffset + i * 12;
|
|
string channelName = Encoding.ASCII.GetString(fileData, channelOffset + 4, 24).TrimEnd('\0');
|
|
|
|
if (channelName.Equals(oldName, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
// 4. 修改通道名称(需填充为 24 字节)
|
|
byte[] newNameBytes = Encoding.ASCII.GetBytes(newName.PadRight(24));
|
|
Array.Copy(newNameBytes, 0, fileData, channelOffset + 4, newNameBytes.Length);
|
|
|
|
// 5. 写回文件
|
|
File.WriteAllBytes(filePath, fileData);
|
|
return;
|
|
}
|
|
}
|
|
|
|
throw new KeyNotFoundException("未找到指定通道");
|
|
}
|
|
}
|
|
}
|