private void ChapterImageContent(HttpListenerContext context) { Regex paramsPattern = new Regex(@"^\?epid=([0-9]+)&start=([0-9]+)$"); Match match = paramsPattern.Match(context.Request.Url.Query); int epid, start; if (!int.TryParse(match.Groups[1].Value, out epid)) { // Request doesn't contain a valid episode id this.ErrorPage404(context); return; } if (!int.TryParse(match.Groups[2].Value, out start)) { // Request doesn't contain a valid start time this.ErrorPage404(context); return; } var download = new Model.Download(epid); var chapter = new Model.Chapter(download, start); CompressedImage image = chapter.Image; if (image == null) { // Specified chapter does not have an image this.ErrorPage404(context); return; } context.Response.ContentType = "image/png"; // Find the appropriate codec for saving the image as a png System.Drawing.Imaging.ImageCodecInfo pngCodec = null; foreach (System.Drawing.Imaging.ImageCodecInfo codec in System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()) { if (codec.MimeType == context.Response.ContentType) { pngCodec = codec; break; } } try { image.Image.Save(context.Response.OutputStream, pngCodec, null); } catch (HttpListenerException) { // Don't worry about dropped connections etc. } }