private void Page_Load(object sender, System.EventArgs e) { // ページを初期化するユーザー コードをここに挿入します。 // 拡張パス情報を得て、商品IDを抽出する string pathinfo = Request.PathInfo; bool thumbflag; // 正規表現を使って拡張パス情報を抽出する Match m = Regex.Match(pathinfo, "^/(\\d{1,10})(s?).jpg$"); if (!m.Success) { // 書式が一致しない // 404エラーを返す Response.StatusCode = (int)HttpStatusCode.NotFound; Response.End(); return; } int productid; try { productid = int.Parse(m.Groups[1].Value); } catch (Exception ex) { // 整数に変換できない if (ex is FormatException || ex is OverflowException ) { // オーバーフローなど // 404エラーを返す Response.StatusCode = (int)HttpStatusCode.NotFound; Response.End(); } else { // その他の不明なエラー // 500エラーを返す Response.StatusCode = (int)HttpStatusCode.InternalServerError; Response.End(); Response.AppendToLog(ex.Message); } return; } if (m.Groups[2].Value == "s") { // 「XXs.jpg」である。つまりサムネイル画像が指定されている thumbflag = true; } else { // 「XX.jpg」である。サムネイル画像ではない thumbflag = false; } // 該当する商品画像をデータベースから取得する SqlConnection sqlconn = new SqlConnection(ConfigurationSettings.AppSettings["DSNSTRING"]); SqlCommand sqlcmd = new SqlCommand("SELECT imgdata FROM Products WHERE id=@id", sqlconn); // パラメータの設定 sqlcmd.Parameters.Add("@id", SqlDbType.Int).Value = productid; // 実行する SqlDataReader sqlreader = null; try { sqlconn.Open(); sqlreader = sqlcmd.ExecuteReader(); if (sqlreader.Read()) { // レコードが存在する if (sqlreader.IsDBNull(0)) { // 画像が存在しない Response.StatusCode = (int)HttpStatusCode.NotFound; Response.End(); } else { // 画像が存在するのでクライアントに返す // 出力データ形式のコンテンツタイプをJPEGに設定 Response.ContentType = "image/pjpeg"; // 画像を読み込む byte [] b = (byte[])sqlreader.GetValue(0); if (!thumbflag) { // サムネイル画像ではない // 読み込んだデータをそのまま返す Response.BinaryWrite(b); } else { // 一度Imageオブジェクトに読み込み、縮小してから返す Bitmap img = null; System.Drawing.Image thumbimg = null; try { img = new Bitmap(new System.IO.MemoryStream(b)); // 縮小する大きさを算出する int smallwidth, smallheight, thumbsize; thumbsize = int.Parse(ConfigurationSettings.AppSettings["ThumbSize"]); // 元画像の幅、高さの大きいほうに合わせる if (img.Width < img.Height) { // 高さのほうが大きい smallheight = thumbsize; smallwidth = img.Width * thumbsize / img.Height; } else { // 幅のほうが大きい smallwidth = thumbsize; smallheight = img.Height * thumbsize / img.Width; } // 縮小画像を生成して書き出す thumbimg = img.GetThumbnailImage(smallwidth, smallheight, null, IntPtr.Zero); thumbimg.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } finally { if (thumbimg != null) { thumbimg.Dispose(); } if (img != null) { img.Dispose(); } } } } } else { // レコードが存在しない Response.StatusCode = (int)HttpStatusCode.NotFound; Response.End(); } } catch (SqlException ex) { // データベースエラー Response.AppendToLog(ex.Message); Response.StatusCode = (int)HttpStatusCode.InternalServerError; Response.End(); } finally { if (sqlreader != null) { sqlreader.Close(); } sqlconn.Close(); } // 出力を閉じて終了 Response.End(); }