Setting the value of a System::Drawing::Imaging::PropertyItem^

352 Views Asked by At

I would like to give my Bitmap a PropertyItem value but i am not really sure how to give it a System::String^ value.

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" cannot be called with the given argument list." Argument types are(System::String^) Object type is System::Drawing::Imaging::PropertyItem^

Hans Passant's answer is correct. I've implemented it like followed:

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]);
1

There are 1 best solutions below

0
On BEST ANSWER

The Value property type is array<Byte>^. That can be anything you want. But a conversion is required and for a string you have to fret a great deal about the encoding you use.

The MSDN docs and PropertyTagTypeASCII makes no bones about it, you are expected to use Encoding::ASCII to make the conversion, use its GetBytes() method to generate the array. But that tends to be a problem, it is where you live, the world does not speak ASCII and you may have to violate the warranty.

In general it is poorly standardized for image meta data, the spec rarely goes beyond specifying an array of bytes and leave it unspecified how it should be interpreted. Practically you can choose between Encoding::Default and Encoding::UTF8 to make the conversion. Encoding::Default is pretty likely to produce a readable string on the same machine on which the image was generated. But if the image is going to travel around the planet then utf8 tends to be the better choice. YMMV. In Germany you'd want to check if glyphs like ß and Ü come out as expected.