0

ここで少し問題があります。

私のページでは、データベースからすべての「プロジェクト」を読み取るために asp:repeater を使用しています。現在、各プロジェクトには 2 つの画像 (バイナリ データ) も含まれており、それらをハンドラーで画像に変換し、ハンドラー ファイルを画像参照として使用したいと考えています。

私はこのコードをウェブで見つけました。それがどのように機能するかも知っていますが、ハンドラーで使用する方法がわかりません:

public Byte[] Ret_image(Int32 id)
{
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "SELECT * FROM Project where Id=@id";
    cmd.Connection = con;
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
    SqlDataReader dr = cmd.ExecuteReader();
    dr.Read();
    Byte[] ar = (Byte[])(dr[1]);
    dr.Close();
    cmd.Dispose();
    return ar;
}

これはおそらくうまくいくと思います。各プロジェクトの ID を指定するだけでよいと思いますが、これを実装する方法がよくわからず、上記のコードが正しいかどうかさえわかりません。

誰でも私を助けることができますか?

前もって感謝します!

[編集]

ハンドラーに必要な ID を与えるにはどうすればよいですか?

<asp:Image ID="img" ImageUrl="Image.ashx" runat="server" Height="80" Width="75%" />

または、ハンドラー内から正しい ID を取得するにはどうすればよいですか?

[編集2]

私は何を間違っていますか?画像は表示されませんが、見つからないとは言いません。

<asp:img class="icon-img icon-img_shadow" src="Image.ashx?ID=<%# DataBinder.Eval(Container, "DataItem.id") %>" alt="Icon" width="152" height="140" />

ハンドラーのコード:

public void ProcessRequest (HttpContext context) {
    int id = Convert.ToInt32(context.Request.QueryString["ID"]);

    context.Response.ContentType = "image/png";
    MemoryStream strm = new MemoryStream(Ret_image(id));
    byte[] buffer = new byte[4096];
    int byteSeq = strm.Read(buffer, 0, 4096);
    while (byteSeq > 0)
    {
        context.Response.OutputStream.Write(buffer, 0, byteSeq);
        byteSeq = strm.Read(buffer, 0, 4096);
    }
}

public Byte[] Ret_image(Int32 id)
{
    SqlConnection sqlCn = new SqlConnection("Data Source=server;Initial Catalog=db;User ID=user;Password=pw");

    string qry = "SELECT * FROM Project WHERE imageid=@id";
    SqlCommand cmd = new SqlCommand(qry, sqlCn);
    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
    SqlDataReader dr = cmd.ExecuteReader();
    sqlCn.Open();
    dr.Read();
    Byte[] ar = (Byte[])(dr[1]);
    dr.Close();
    cmd.Dispose();
    sqlCn.Close();
    return ar;
}
4

2 に答える 2

3

画像 URL としてターゲットとする ashx ページを作成する必要があります。

次に、そのハンドラー内の ProcessRequest メソッドでバイト配列を応答ストリームとして書き込む必要があります...次のようなもの:

context.Response.ContentType = "image/jpeg";
strm = new MemoryStream(ar);   // ar here is your variable from Byte[] ar = (Byte[])(dr[1])
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
    context.Response.OutputStream.Write(buffer, 0, byteSeq);
    byteSeq = strm.Read(buffer, 0, 4096);
}
于 2012-08-16T09:34:46.737 に答える
0

MemoryStreamクラスを使用して、バイト配列をコンストラクターのパラメーターとして渡すだけです。

 MemoryStream ms = new MemoryStream(byteArrayIn);
 Image returnImage = Image.FromStream(ms);
 return returnImage;
于 2012-08-16T09:30:38.927 に答える