0

我的项目允许管理员为军官档案添加勋章,目前我最多只能插入 5 个勋章。但是我的老师要求我让管理员在军官档案中插入他们想要的尽可能多的奖章。我不确定如何检索管理员插入的所有图像,我知道如何使用 varbinary 将图像插入数据库。请给我这样做的方法。谢谢!

下面的代码是我如何插入最多 5 个奖牌:

上传代码:

System.Drawing.Image uploaded = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);

System.Drawing.Image newImage = new Bitmap(1024, 768);
using (Graphics g = Graphics.FromImage(newImage))
{
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.DrawImage(uploaded, 0, 0, 1024, 768);
}

byte[] results;
using (MemoryStream ms = new MemoryStream())
{
    ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
    EncoderParameters jpegParms = new EncoderParameters(1);
    jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
    newImage.Save(ms, codec, jpegParms);
    results = ms.ToArray();
}

string sqlImage = "Insert into OfficerMedal(policeid, image) values ('" + Session["policeid"] + "', @Data)";
SqlCommand cmdImage = new SqlCommand(sqlImage);
cmdImage.Parameters.AddWithValue("@Data", results);
InsertUpdateData(cmdImage);

我使用 aspx 页面检索图像

protected void Page_Load(object sender, EventArgs e)
    {
        string strQuery = "select image from OfficerMedal where policeid='" + Session["policeid"] + "'";
        SqlCommand cmd = new SqlCommand(strQuery);
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            download(dt);
        }
    }

    private DataTable GetData(SqlCommand cmd)
    {
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        SqlDataAdapter sda = new SqlDataAdapter();
        cmd.CommandType = CommandType.Text;
        cmd.Connection = con;
        try
        {
            con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            return dt;
        }
        catch
        {
            return null;
        }
        finally
        {
            con.Close();
            sda.Dispose();
            con.Dispose();
        }
    }

    private void download(DataTable dt)
    {
        // check if you have any rows at all 
        // no rows -> no data to convert!
        if (dt.Rows.Count <= 0)
            return;

        // check if your row #0 even contains data -> if not, you can't do anything!
        if (dt.Rows[0].IsNull("image"))
            return;

        Byte[] bytes = (Byte[])dt.Rows[0]["image"];
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "image/jpg";
        Response.BinaryWrite(bytes);
        Response.End();
    }

要添加此当前方法,我从数据库中逐个检索图像。而不是检索属于该官员的所有图像。

4

1 回答 1

0

执行此操作的常用方法是使用 aHttpHandler而不是在您的 ASPX 页面本身中。处理程序负责从您的数据库中检索图像数据并将其作为图形输出;然后它可以用作src常规<img>标记或控件的ImageUrl属性<asp:image>

添加处理程序的最简单方法是在“添加新项”对话框中选择通用处理程序: 添加新项目

在处理程序的代码中,ProcessRequest 是完成工作的方法,例如

public void ProcessRequest(HttpContext context)
{
    byte[] imageBytes;
    // Get the id of the image we want to show
    string imageId = context.Request.QueryString["ImageId"];

    // Get the image bytes out of the database
    using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    {
        // Pass in the image id we got from the querystring
        SqlCommand cmd = new SqlCommand("SELECT image FROM PoliceMedal WHERE ImageId=" + imageId, conn);
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        reader.GetBytes(0, 0, imageBytes, 0, int.MaxValue);
    }

    context.Response.Buffer = true;
    context.Response.Charset = "";
    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    context.Response.ContentType = "image/jpg";
    context.Response.BinaryWrite(imageBytes);
    context.Response.End();
}

所以我们有我们的处理程序,它将从数据库中返回图像数据,我们用一个类似的 url 来调用它\ImageHandler.ashx?ImageId=1。这确实需要更改您的数据库,因为您需要向 PoliceMedal 表添加一个键 - 我建议使用 SQL ServerIDENTITY列。

从您的问题中不清楚您如何在 ASPX 页面上显示图像,所以在这里我将向您展示如何将它们添加到PlaceHolder. 因此,我们将检索军官的图像 ID 集,<asp:image>为它们中的每一个构造一个控件并将图像添加到 PlaceHolder。

protected void Page_Load(object sender, EventArgs e)
{
    using (
        SqlConnection conn =
            new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
    {
        // Query the table to get the list of image IDs for the current user
        SqlCommand cmd = new SqlCommand("SELECT ImageId FROM PoliceMedal WHERE policeid = " + Session["policeid"], conn);
        conn.Open();
        SqlDataReader imageReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        // For each image in the database
        while (imageReader.Read())
        {
            // Create the new Image control
            Image medalImage = new Image();
            // Call the handler, passing the id of the image in the querystring
            medalImage.ImageUrl = string.Format("ImageHandler.ashx?ImageId={0}",
                                                imageReader.GetInt32(0));
            // Add the image to the placeholder
            MedalPlaceHolder.Controls.Add(medalImage);
        }
    }
}
于 2013-10-02T16:11:44.617 回答