同时设置属性值和位图分辨率,然后重新保存图像应该会改变分辨率(它适用于我的示例图像)。我相信原始文件必须存在 X 和 Y 分辨率的标签,如果不存在,不确定 .NET 是否会添加这些标签(必须测试)。
这是一个使用 .NET 读取和写入 TIFF 图像的 X 和 Y 分辨率的示例:
int numerator, denominator;
using (Bitmap bmp = (Bitmap)Bitmap.FromFile(@"C:\input.tif"))
{
// obtain the XResolution and YResolution TIFFTAG values
PropertyItem piXRes = bmp.GetPropertyItem(282);
PropertyItem piYRes = bmp.GetPropertyItem(283);
// values are stored as a rational number - numerator/denominator pair
numerator = BitConverter.ToInt32(piXRes.Value, 0);
denominator = BitConverter.ToInt32(piXRes.Value, 4);
float xRes = numerator / denominator;
numerator = BitConverter.ToInt32(piYRes.Value, 0);
denominator = BitConverter.ToInt32(piYRes.Value, 4);
float yRes = numerator / denominator;
// now set the values
byte[] numeratorBytes = new byte[4];
byte[] denominatorBytes = new byte[4];
numeratorBytes = BitConverter.GetBytes(600); // specify resolution in numerator
denominatorBytes = BitConverter.GetBytes(1);
Array.Copy(numeratorBytes, 0, piXRes.Value, 0, 4); // set the XResolution value
Array.Copy(denominatorBytes, 0, piXRes.Value, 4, 4);
Array.Copy(numeratorBytes, 0, piYRes.Value, 0, 4); // set the YResolution value
Array.Copy(denominatorBytes, 0, piYRes.Value, 4, 4);
bmp.SetPropertyItem(piXRes); // finally set the image property resolution
bmp.SetPropertyItem(piYRes);
bmp.SetResolution(600, 600); // now set the bitmap resolution
bmp.Save(@"C:\output.tif"); // save the image
}