简体   繁体   English

显示从数据库检索的多个图像

[英]Displaying multiple image retrieving from database

My project allow admin to add medal for officer profile, currently I only able to insert the maximum of 5 medals. 我的项目允许管理员为人员资料添加奖牌,目前我最多只能插入5枚奖牌。 But my teacher ask me to let the admin insert as many medal as they want for the officer profile. 但是我的老师要求我让管理员为他们的军官简介插入尽可能多的奖牌。 I not sure how do I retrieve all the image that the admin inserted, I know how to insert image into database using varbinary. 我不确定如何检索管理员插入的所有图像,我知道如何使用varbinary将图像插入数据库。 Do give me way for doing this. 请给我这样做的方法。 THANKS! 谢谢!

Code Below is how I do for inserting at maximum of 5 medals: 以下代码是我最多插入5枚奖牌的方法:

Code for uploading: 上传代码:

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);

I retrieve image using aspx page 我使用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();
    }

To add on for this current method I retrieving image 1 by 1 from database. 为了添加当前方法,我从数据库中检索图像1比1。 Instead of retrieving all image that belong to the officer. 而不是检索属于该官员的所有图像。

The usual way to do this is with a HttpHandler rather than in your ASPX page itself. 通常的方法是使用HttpHandler而不是使用ASPX页面本身。 The handler is responsible for retrieving the image data from your database and outputting it as a graphic; 处理程序负责从数据库中检索图像数据并将其输出为图形; it can then be used as the src for a regular <img> tag or the ImageUrl property for an <asp:image> control. 然后可以将其用作常规<img>标记的src<asp:image>控件的ImageUrl属性。

The easiest way to add a handler is to select Generic Handler in the Add New Item dialog: 添加处理程序的最简单方法是在“添加新项”对话框中选择“通用处理程序”: 新增项目

In the code for the handler, ProcessRequest is the method that does the work eg 在处理程序的代码中,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();
}

So we have our handler that will return the image data from the database, and we call this with a url like \\ImageHandler.ashx?ImageId=1 . 因此,我们有了处理程序,该处理程序将从数据库返回图像数据,并使用\\ImageHandler.ashx?ImageId=1类的url进行调用。 This does require a change to your database in that you'll need to add a key to the PoliceMedal table - I suggest a SQL Server IDENTITY column. 这确实需要更改数据库,因为您需要向PoliceMedal表添加密钥-我建议使用SQL Server IDENTITY列。

It's not clear from your question how you're displaying the images on the ASPX page, so here I'll just show you how to add them into a PlaceHolder . 从您的问题尚不清楚,您是如何在ASPX页面上显示图像的,所以在这里,我仅向您展示如何将它们添加到PlaceHolder So, we'll retrieve the set of image ids for an officer, construct an <asp:image> control for each of them and add the images to the PlaceHolder. 因此,我们将获取官员的图像ID集,为每个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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM