Parameter is not valid error when creating image from byte[] in c#

前端 未结 4 1931

I am trying to convert a byte[] to Bitmap in c#. Following is the code:

MemoryStream ms = new MemoryStream(b);
Bitmap bmp = new Bit         


        
相关标签:
4条回答
  • 2020-12-05 21:19

    Error is shown if you are disposing the image. Try removing that from code

    0 讨论(0)
  • 2020-12-05 21:27

    Okay, just to clarify things a bit... the problem is that new Bitmap(ms) is going to read the data from the stream's current position - if the stream is currently positioned at the end of the data, it's not going to be able to read anything, hence the problem.

    The question claims that the code is this:

    MemoryStream ms = new MemoryStream(b);
    Bitmap bmp = new Bitmap(ms);
    

    In that case there is no requirement to reset the position of the stream, as it will be 0 already. However, I suspect the code is actually more like this:

    MemoryStream ms = new MemoryStream();
    // Copy data into ms here, e.g. reading from NetworkStream
    Bitmap bmp = new Bitmap(ms);
    

    or possibly:

    MemoryStream ms = new MemoryStream(b);
    // Other code which *reads* from ms, which will change its position,
    // before we finally call the constructor:
    Bitmap bmp = new Bitmap(ms);
    

    In this case you do need to reset the position, because otherwise the "cursor" of the stream is at the end of the data instead of the start. Personally, however, I prefer using the Position property instead of the Seek method, just for simplicity, so I'd use:

    MemoryStream ms = new MemoryStream();
    // Copy data into ms here, e.g. reading from NetworkStream
    
    // Rewind the stream ready for reading
    ms.Position = 0;
    Bitmap bmp = new Bitmap(ms);
    

    It just goes to show how important it is that the sample code in a question is representative of the actual code...

    0 讨论(0)
  • 2020-12-05 21:39

    Try resetting current location in the stream

    MemoryStream ms = new MemoryStream(b);
    ms.Seek(0, SeekOrigin.Begin);
    Bitmap bmp = new Bitmap(ms);
    
    0 讨论(0)
  • 2020-12-05 21:41

    Try like this:

    byte[] b = ...
    using (var ms = new MemoryStream(b))
    using (var bmp = Image.FromStream(ms))
    {
        // do something with the bitmap
    }
    
    0 讨论(0)
提交回复
热议问题