在C#中我试图在jpg文件中设置下面的属性。但是当我尝试检索它们时,我得到了Property not found异常。此外,SetPropertyItem调用无法报告成功\失败,因此很难理解出现了什么问题。
0x5111 PropertyTagPixelPerUnitX
0x5112 PropertyTagPixelPerUnitY
string file = "New.jpg";
double x = 24524.5555598;
double y = 234123.4123423;
Image img = Image.FromFile(file);
PropertyItem[] props = img.PropertyItems;
PropertyItem newProp1 = props.FirstOrDefault();
newProp1.Id = 0x5111;
newProp1.Type = 1;
newProp1.Value = BitConverter.GetBytes(x);
newProp1.Len = newProp1.Value.Length;
PropertyItem newProp2 = props.FirstOrDefault();
newProp2.Id = 0x5112;
newProp2.Type = 1;
newProp2.Value = BitConverter.GetBytes(y);
newProp2.Len = newProp1.Value.Length;
img.SetPropertyItem(newProp1);
img.SetPropertyItem(newProp2);
img.Save("New1.jpg", ImageFormat.Jpeg);
检索它们的代码,
string file = "New1.jpg";
Image img = Image.FromFile(file);
PropertyItem prop = img.GetPropertyItem(0x5111);
以上行引发异常'Property not found'
答案 0 :(得分:4)
我不知道为什么他们将PropertyItem构造函数设置为内部,并且没有提供任何其他创建属性项的方法。但是你可以使用反射来解决这个奇怪的问题,它会起作用:
string file = @"New1.jpg";
double x = 24524.5555598;
double y = 234123.4123423;
var img = System.Drawing.Image.FromFile(file);
// note how to force Activator.CreateInstance to call internal constructor,
// it's important to call this overload
var newProp1 = (PropertyItem) Activator.CreateInstance(typeof(PropertyItem), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[0], CultureInfo.InvariantCulture);
newProp1.Id = 0x5111;
newProp1.Type = 1;
newProp1.Value = BitConverter.GetBytes(x);
newProp1.Len = newProp1.Value.Length;
var newProp2 = (PropertyItem)Activator.CreateInstance(typeof(PropertyItem), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[0], CultureInfo.InvariantCulture);
newProp2.Id = 0x5112;
newProp2.Type = 1;
newProp2.Value = BitConverter.GetBytes(y);
newProp2.Len = newProp1.Value.Length;
img.SetPropertyItem(newProp1);
img.SetPropertyItem(newProp2);
img.Save("New1.jpg", ImageFormat.Jpeg);