I'm trying to set dpi value of a TIFF Image in C# through code but somehow the values are not persisted after saving the 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
}
What is wrong with this code? Any kind of help would be appreciated.
TIFF file tag definitions
解决方案
Setting both the property value and the bitmap resolution and then resaving the image should change the resolution (It worked on my sample image). I believe the original file has to have the tags for X and Y resolution present, not sure if .NET will add those tags if not present (would have to test).
Here's an example of reading and writing the X and Y resolution a TIFF image using .NET:
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
}