0

I save panel as an image in database by using this code:

public Form2()
{
    InitializeComponent();
}

public static byte[] ImageToByte2(Bitmap img)
{
    byte[] byteArray = new byte[0];

    using (MemoryStream stream = new MemoryStream())
    {
        img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        stream.Close();

        byteArray = stream.ToArray();
    }

    return byteArray;
}

private void button1_Click(object sender, EventArgs e)
{
    Form1 fom = new Form1();

    Bitmap bitmap = new Bitmap(fom.panel1.ClientSize.Width,
                          fom.panel1.ClientSize.Height);

    fom.panel1.DrawToBitmap(bitmap, fom.panel1.ClientRectangle);

    byte[] imgArray = ImageToByte2(bitmap);

    ImageData img = new ImageData
    {
        ClassName = textBox1.Text,
        Password = textBox2.Text,
        Image = imgArray,
    };

    using (BoardDatabaseEntities dc = new BoardDatabaseEntities())
    {
        dc.ImageDatas.Add(img);
        dc.SaveChanges();
        MessageBox.Show("Saved into database");      
    }

    this.Close();
}

I am trying display images from database on webpage (view control) but no success yet. There are many source codes on internet but they all upload a file. Codes are for UploadedFile. I just can't figure out how to make it (those codes) suitable for my situation. Could you please help?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Uluz
  • 41
  • 1
  • 1
  • 7

2 Answers2

2

The general practice is that you have some sort of handler that retrieves the image from the database and provides them to the client. In order to know what image to retrieve, you'll need the primary keys. In order to provide the correct MIME type, you'll need to pull that data from the database.

Add a generic handler (.ashx) to your project.

public class Handler : IHttpHandler
{

    public void ProcessRequest (HttpContext context)
    {

        string ImageId = context.Request.QueryString["Id"]; //you'll want to do defensive coding and make sure this query string variable exists



        byte[] ImageBytes = Database.GetImageBytes(ImageId); //I assume you know how to retrieve the byte array from the database?
        string MimeType = Database.GetMimeType(ImageId);

        context.Response.ContentType = MimeType;
        context.Response.BinaryWrite(ImageBytes);
    }

    public bool IsReusable { get { return false; } }
}

Then on the page, you'll just put the URL to that handler for the image's source.

<asp:Image runat="server" ImageUrl="~/RetrieveImage.ashx?Id=505874" />
mason
  • 31,774
  • 10
  • 77
  • 121
0

One solution would be to convert the byte array into a base64 encoded string and then send it to the view.

Converting image into data:image/png;base64 for web page disaplay

Community
  • 1
  • 1
soaP
  • 101
  • 5