Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from string to Image in C#

Tags:

string

c#

image

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;
    }
like image 887
user2528880 Avatar asked Jun 27 '13 16:06

user2528880


People also ask

How to convert ToBase64String?

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.

Can we convert image to string?

String img=o. toString(); byte[] imageAsBytes = Base64. decode(img. getBytes(), Base64.


1 Answers

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.

like image 142
Jeff Foster Avatar answered Oct 23 '22 07:10

Jeff Foster