tags:

views:

109

answers:

1

I am using WPF to load an image in the background using the answer at Stackoverflow: How do I load images in the background?

The problem is the URL string could be PNG, GIF or JPG and I need to use either JpegBitmapDecoder, PngBitmapDecoder or GifBitmapDecoder If the correct decoder is not used then a FileFormatException occurs.

I could use the extension on the string but errors could still occur if the user has a GIF image with a .png extension.

Any ideas how I would resolve this issue?

A: 

You could binary read the start part of the file itself and compare it witht the various file specifications.

I got this from just checking some JPG files without reading the specs, and it is only a very rudimentary match pattern, so it's not to be trusted, but just as an example (in real apps you should not read whole the stream of course ):

let IsJpg (url:string) =
    let req = WebRequest.Create(url)
    let rsp = req.GetResponse()
    use stream = rsp.GetResponseStream()
    use reader = new StreamReader(stream)       
    let GetResult = reader.ReadToEnd()
    GetResult.Contains("JFIF")

So the first 2 will yield true, and the third false :

IsJpg "http://www.flatpackrevolution.com/wp-content/uploads/2007/10/pow.jpg" 
IsJpg   "http://bedzine.com/blog/wp-content/uploads/2008/04/4-17-stack-drawers-1-1.jpg"
IsJpg "http://sstatic.net/so/img/logo.png"
Peter