i have the following code:
var request = (HttpWebRequest)HttpWebRequest.Create(url);
var response = request.GetResponse();
var stream = response.GetResponseStream();
if (stream != null) {
Image newImage = Image.FromStream(stream, true);
pic.Thumb = newImage.ImageToByteArray();
}
Wha开发者_如何学运维t happens if the read times out? Or the connection is aborted mid-download?
The docs say that it will throw an ArgumentException
if it's not a valid format or is null, but I have no idea if it will throw that exception if the image is only partially downloaded.
Unfortunately, I can't rely on the ContentLength header to tell me the proper size of the file, because the server lies and gives a larger content length than the file actually is. So my hope is that Image.FromStream will be able to tell if the image is complete or not.
Can anyone provide some insight here?
Note: ImageToByteArray is just an extension method that uses a memory stream to convert the Image
to a byte[]
UPDATE:
According to Darin, then an ExternalException gets thrown when you try to save the image. However, my own testing in which I truncated an image file shows that FromStream
does in fact throw an ArgumentException if the image is not the correct number of bytes.
What happens if the read times out?
An exception will be thrown before entering the if
condition.
Or the connection is aborted?
An exception will be thrown before entering the if
condition.
but I have no idea if it will throw that exception if the image is only partially downloaded.
An image cannot be partially downloaded. The GetResponseStream
is a blocking method meaning that either you get everything, or an exception (or of course in your case you could also get an exception if what you fetched is not an image but some HTML page which will happen when you try to instantiate the Image GDI+ object).
As a side note, to avoid leaking, you probably also want to wrap this Image
disposable resource into a using
statement.
精彩评论