Converting from string to Image in C#

前端 未结 5 2078
生来不讨喜
生来不讨喜 2021-02-20 06:22

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


        
5条回答
  •  无人共我
    2021-02-20 06:55

    Take out your call that writes to the MemoryStream. The constructor call that accepts a byte array automatically puts the contents of the byte array into the stream. Otherwise your stream contains 2 copies of the raw data. In addition, the call to Write will leave the stream's position at the end of stream, so there is no data that the FromStream call can read.

    So it would be:

    public Image stringToImage(string inputString)
    {
        byte[] imageBytes = Encoding.Unicode.GetBytes(inputString);
    
        // Don't need to use the constructor that takes the starting offset and length
        // as we're using the whole byte array.
        MemoryStream ms = new MemoryStream(imageBytes);
    
        Image image = Image.FromStream(ms, true, true);
    
        return image;
    }
    

提交回复
热议问题