2

我想给我的位图一个 PropertyItem 值,但我不确定如何给它一个 System::String^ 值。

System::Drawing::Imaging::PropertyItem^ propItem = gcnew System::Drawing::Imaging::PropertyItem;
System::String^ newValue = gcnew System::String("newValue");

propItem->Id = PropertyTagImageTitle;
propItem->Len = 9;
propItem->Type = PropertyTagTypeASCII;
propItem->Value = newValue;
bmp->SetPropertyItem(propItem);

"System::Drawing::Imaging::PropertyItem::Value::set" 不能用给定的参数列表调用。” 参数类型是(System::String^) 对象类型是 System::Drawing::Imaging::属性项^

Hans Passant 的回答是正确的。我已经实现了它,如下所示:

System::Drawing::Image^ theImage = System::Drawing::Image::FromFile("C:\\image.png");
System::Text::Encoding^ utf8 = System::Text::Encoding::UTF8;
array<System::Drawing::Imaging::PropertyItem^>^ propItem = theImage->PropertyItems;
System::String^ newValue = gcnew System::String("newValue");
propItem->Id = PropertyTagImageTitle;
propItem[0]->Len = 18;
propItem->Type = PropertyTagTypeByte;

array<Char>^propItemValue = newValue->ToCharArray();
array<byte>^ utf8Bytes = utf8->GetBytes(propItemValue);
propItem[0]->Value = utf8Bytes;
theImage->SetPropertyItem(propItem[0]);
4

1 回答 1

4

值属性类型是array<Byte>^。那可以是你想要的任何东西。但是需要进行转换,对于字符串,您必须非常担心您使用的编码。

MSDN 文档并PropertyTagTypeASCII对此毫不含糊,您应该使用Encoding::ASCII进行转换,使用它的 GetBytes() 方法生成数组。但这往往是一个问题,它是你居住的地方,世界不会说 ASCII,你可能不得不违反保修。

一般来说,图像元数据的标准化很差,规范很少超出指定字节数组的范围,并且未指定应如何解释它。实际上,您可以在 Encoding::Default 和 Encoding::UTF8 之间进行选择来进行转换。Encoding::Default 很可能在生成图像的同一台机器上生成可读字符串。但是,如果图像要在地球上传播,那么 utf8 往往是更好的选择。YMMV。在德国,您需要检查像 ß 和 Ü 这样的字形是否按预期出现。

于 2018-08-16T09:11:19.250 回答