0

我正在使用 JPG 图像类型,这条线image = Image.FromStream(ms);给出了错误Parameter is not valid。这段代码有什么问题?

        private void button3_Click(object sender, EventArgs e)
        {
          Image partial=null;
          Rectangle bounds;
          Guid id;

          if (diff != null)
          {
            ImageConverter converter = new ImageConverter();
            var data = (byte[])converter.ConvertTo(diff, typeof(byte[]));

            UnpackScreenCaptureData(data, out partial, out bounds,out id);
            Image imgfirst = (Image)firstImg;
            UpdateScreen(ref imgfirst, partial, bounds);
          }
        }

        public static void UnpackScreenCaptureData(byte[] data, out Image image, out Rectangle bounds, out Guid id)
        {
          // Unpack the data that is transferred over the wire.
          // Create byte arrays to hold the unpacked parts.
          const int numBytesInInt = sizeof(int);
          int idLength = Guid.NewGuid().ToByteArray().Length;
          int imgLength = data.Length - 4 * numBytesInInt - idLength;
          byte[] topPosData = new byte[numBytesInInt];
          byte[] botPosData = new byte[numBytesInInt];
          byte[] leftPosData = new byte[numBytesInInt];
          byte[] rightPosData = new byte[numBytesInInt];
          byte[] imgData = new byte[imgLength];
          byte[] idData = new byte[idLength];

          // Fill the byte arrays.
          Array.Copy(data, 0, topPosData, 0, numBytesInInt);
          Array.Copy(data, numBytesInInt, botPosData, 0, numBytesInInt);
          Array.Copy(data, 2 * numBytesInInt, leftPosData, 0, numBytesInInt);
          Array.Copy(data, 3 * numBytesInInt, rightPosData, 0, numBytesInInt);
          Array.Copy(data, 4 * numBytesInInt, imgData, 0, imgLength);
          Array.Copy(data, 4 * numBytesInInt + imgLength, idData, 0, idLength);

          // Create the bitmap from the byte array.          
          MemoryStream ms = new MemoryStream(imgData, 0, imgData.Length);
          ms.Write(imgData, 0, imgData.Length);
          image = Image.FromStream(ms);
          ....
        }
4

1 回答 1

0

我认为您必须将您MemoryStream的位置重置为 0。您可以通过调用Seek()内存流上的方法来完成此操作:

MemoryStream ms = new MemoryStream(imgData, 0, imgData.Length);
ms.Write(imgData, 0, imgData.Length);

ms.Seek(0, SeekOrigin.Begin);  // Set stream position to 0.    

image = Image.FromStream(ms);
于 2012-12-13T18:39:04.023 回答