gpt4 book ai didi

C# 设置和获取 JPG 中的 PropertyItem 'Property not found' 异常

转载 作者:行者123 更新时间:2023-11-30 20:40:57 26 4
gpt4 key购买 nike

在 C# 中,我试图在 jpg 文件中设置以下属性。但是当我尝试取回它们时,我得到了 Property not found 异常。此外,SetPropertyItem 调用无法报告成功\失败,因此很难理解哪里出了问题。

0x5111PropertyTagPixelPerUnitX

0x5112PropertyTagPixelPerUnitY

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'

最佳答案

我不明白为什么他们将 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);

关于C# 设置和获取 JPG 中的 PropertyItem 'Property not found' 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32761091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com