繁体   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