ページの読み込み時に画像を返す ASHX ハンドラーがあります。画像のサイズに応じて動的にクラスを画像に追加する必要があります。次の方法を使用してこれを実行しようとしました。
コード ビハインド メソッド
cs
protected void Page_Load(object sender, EventArgs e)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
image1.ImageUrl = "get_image.ashx?id=" + id;
}
public void classify_image_Load(object sender, EventArgs e)
{
if(image1.Width.Value > image1.Height.Value)
{
image1.CssClass = "landscape";
}
else
{
image1.CssClass = "portrait";
}
}
html
<asp:Image ID="image1" runat="server" OnLoad="classify_image_Load" />
これは初期ロードでは機能しますが、ポストバック (新しい画像のアップロード/回転/クロッピング) では、クラスを正しく適用できません。
jQuery メソッド
js
$(window).load(function(){
$('#image1').load(function() {
if($(this).width() > $(this).height())
{
$(this).attr('class', 'landscape');
} else {
$(this).attr('class', 'portrait');
}
});
});
この方法はまったく機能しません。画像にはクラスが割り当てられていません。これが ashx コントロールのタイミングの問題かどうかはわかりません。
ASHX コード
public class get_image : IHttpHandler
{
string file_path = ConfigurationManager.AppSettings["file_path"].ToString();
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
Image img;
if (!String.IsNullOrEmpty(context.Request.QueryString["id"]))
{
int id;
if (context.Request.QueryString["id"].IndexOf('?') > 0)
{
id = Int32.Parse(context.Request.QueryString["id"].Split('?')[0]);
}
else
{
id = Int32.Parse(context.Request.QueryString["id"]);
}
dbclassDataContext db = new dbclassDataContext();
photo d = (from p in db.photos
where p.id == id
select p).SingleOrDefault();
if (d != null)
{
if (!String.IsNullOrEmpty(d.filename))
{
img = Image.FromFile(file_path + "\\" + d.filename);
context.Response.ContentType = "image/" + d.filetype;
img.Save(context.Response.OutputStream, get_format(d.filetype));
}
else
{
img = Image.FromFile(file_path + "\\no_image.jpg");
context.Response.ContentType = "image/jpeg";
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
else
{
img = Image.FromFile(file_path + "\\no_image.jpg");
context.Response.ContentType = "image/jpeg";
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
else
{
img = Image.FromFile(file_path + "\\no_image.jpg");
context.Response.ContentType = "image/jpeg";
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
img.Dispose();
}
public bool IsReusable
{
get
{
return false;
}
}
private ImageFormat get_format(string ftype)
{
switch (ftype)
{
case "jpeg":
return ImageFormat.Jpeg;
case "png":
return ImageFormat.Png;
case "gif":
return ImageFormat.Gif;
default:
return ImageFormat.Jpeg;
}
}
}
Linq を使用して、ユーザー ID に基づいてデータベースから場所とタイプを取得し、要求元のページに画像を返します。これは問題なく動作しているようですが、見落としがある可能性がある場合に備えて含めました。
質問
ディメンションに基づいて画像を動的に分類する必要があります。これは、.NET コード ビハインドまたは jQuery を使用して行うことができます。上記の方法が正しく機能しない原因は何ですか?