I am trying to convert a Unicode string to an image in C#. Each time I run it I get an error on this line
Image image = Image.FromStream(ms, true, true);
that says: ArgumentException was unhandled by user code. Parameter is not valid. Any ideas why this is happening? Below is the rest of the function.
public Image stringToImage(string inputString)
{
byte[] imageBytes = Encoding.Unicode.GetBytes(inputString);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true, true);
return image;
}
ToBase64String(Byte[], Int32, Int32) Converts a subset of an array of 8-bit unsigned integers to its equivalent string representation that is encoded with base-64 digits. Parameters specify the subset as an offset in the input array, and the number of elements in the array to convert.
String img=o. toString(); byte[] imageAsBytes = Base64. decode(img. getBytes(), Base64.
Unicode doesn't encode all possible byte sequences that you'll need to represent an image.
byte[]
-> String
-> byte[]
is a transformation that just won't work for many given sequences of bytes. You'll have to use a byte[] throughout.
For example, if you read the bytes, convert them to UTF-16 then it's possible that byte sequences will be discarded as invalid. Here's an example of an invalid byte sequence from UTF-16.
Code points U+D800 to U+DFFF[edit] The Unicode standard permanently reserves these code point values for UTF-16 encoding of the lead and trail surrogates, and they will never be assigned a character, so there should be no reason to encode them. The official Unicode standard says that all UTF forms, including UTF-16, cannot encode these code points.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With