在C#中将DPI值设置为Tiff图像

Pra*_*dda 2 c# tiff image-processing

我试图TIFF通过代码在C#中设置Image的dpi值,但不知何故,保存Image后值不会保留.

using (var image = new Bitmap(@"c:\newimage.tif"))
{
    uint[] uintArray = { 300, 1}; //Setting DPI as 300
    byte[] bothArray = ConvertUintArrayToByteArray(uintArray);
    PropertyItem item = image.PropertyItems.Where(p => p.Id == 0x11A).Single();
    var val = BitConverter.ToUInt32(item.Value, 0);
    Console.WriteLine(val);
    item.Id = 0x11A;
    item.Value = bothArray;
    item.Type = 5;
    item.Len = item.Value.Length;
    image.SetPropertyItem(item);
    image.Save(@"c:\newimage1.tif"); //Save image to new File
}
Run Code Online (Sandbox Code Playgroud)

这段代码有什么问题?任何形式的帮助将不胜感激. TIFF文件标记定义

小智 5

设置属性值和位图分辨率然后重新保存图像应该改变分辨率(它在我的样本图像上工作).我相信原始文件必须包含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
}
Run Code Online (Sandbox Code Playgroud)