簡體   English   中英

圖像處理時Image.FromStream()發出C#

[英]Image.FromStream() issue C# at the time of image manipulation

我正在使用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);
          ....
        }

我認為您必須將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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM