我正在使用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);
....
}
答案 0 :(得分:1)
我认为您必须将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);