0

我将显示来自数据库的图像作为用户输入图像 ID。我必须在它下面的图片框中显示它。

我使用此代码将 base64string 转换为图像

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["ImageID"] != null)
        {
            string ImgData = Request.QueryString["ImageID"].ToString();
            Byte[] bytes = Convert.FromBase64String(ImgData);
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "image/jpg";
            Response.AddHeader("content-disposition", "attachment;");
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }
}

我的主要网页源代码是

protected void Button1_Click(object sender, EventArgs e)
    {
        NpgsqlCommand cmd = null;
        string selPhoto = @"select * from photodetails where photoid=@photoid";
        System.Drawing.Image newImage;
        string tempfilename=@"C:\Users\Public\temp_image";
        try
        {
            cmd = new NpgsqlCommand(selPhoto, con);

            cmd.Parameters.Add("@photoid",Convert.ToInt16(txtpid.Text));
            if (con.State == ConnectionState.Open)
                con.Close();
            con.Open();

            NpgsqlDataReader drphoto = cmd.ExecuteReader();
            while (drphoto.Read())
            {
                //System.IO.Stream fs = FileUpload1.PostedFile.InputStream;
                //System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
                Byte[] bytes = (byte[])drphoto["photo_bytearr"]; //br.ReadBytes((Int32)fs.Length);
                string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
                img1.ImageUrl = @"http://localhost:29450/SampleWeb/showimg.aspx?ImageData=" + Convert.ToBase64String(bytes);                
            }

        }
        catch (Exception ex)
        {

        }
    }

但它仍然不显示图像?

4

1 回答 1

2

以下行将不起作用。

img1.ImageUrl = @"http://localhost:29450/SampleWeb/showimg.aspx?ImageData=" + Convert.ToBase64String(bytes);

而是传递图像的 id 并进行查找,而不是尝试通过 url 传递二进制数据。

img1.ImageUrl = @"http://localhost:29450/SampleWeb/showimg.aspx?ImageId=" + imageId; 

注意:Internet Explorer 将只允许在您的 url 中包含 2,048 个字符。

于 2013-07-26T13:20:05.467 回答