Parameter is not valid - creating Picture from MemoryStream


#1

Hi all

I've got the following code to add a picture in to a presentation using a URI:

//Get the image from the imgLoc URI

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgLoc);

using (HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse())

{

//Put the response in to a standard stream

Stream tempImg = httpWebResponse.GetResponseStream();

//Convert the response stream into a MemoryStream as HttpResponses are non-seekable

Byte[] tempBytes = new Byte[1024];

MemoryStream imageStream = new MemoryStream();

int bytesRead = tempImg.Read(tempBytes, 0, tempBytes.Length);

while (bytesRead > 0)

{

imageStream.Write(tempBytes, 0, tempBytes.Length);

bytesRead = tempImg.Read(tempBytes, 0, tempBytes.Length);

}

//Close the HttpResponse stream

tempImg.Close();

//Add the picture to the presentation

pic = new Picture(pres, imageStream);

//Close the MemoryStream

imageStream.Close();

}

This works fine when adding a thumbnail image (Stream size = 3,072), but when adding the full size image (Stream size = 3,385,344) I'm getting a 'Parameter is not valid' error. They're both jpegs and the URIs are definitely correct (URIs are correct and stream is getting created).

Is there a size limit when creating a Picture, or am a missing something?

Thanks

Ben



#2

There are even 2 bugs.

1. You always write to memory stream 1024 bytes.
tempImg.Read can read any number of bytes from 1 to 1024.
So while loop should be:

while (bytesRead > 0)
{
imageStream.Write(tempBytes, 0, bytesRead);
bytesRead = tempImg.Read(tempBytes, 0, tempBytes.Length);
}

2. You didn’t set position of the stream to 0 before reading. You should add

imageStream.Position = 0;

before line

pic = new Picture(pres, imageStream);


#3

Hi Alexey

Thanks for the swift response, that's fixed it.

I knew I was missing something, think it's probably sleep :-)

Cheers

Ben