Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Is it possible to retrieve different image formats from database using generic handler?
Posted
Updated 12-Nov-13 8:37am
v2
Comments
Kornfeld Eliyahu Peter 10-Oct-13 11:44am    
You mean to load the binary data stored in database into a image object without knowing the image format first?
NitishBharadwaj 10-Oct-13 15:33pm    
Yes...

C#
using System;
using System.Web;
using System.IO;
public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) 
    {
        Int32 regno;
        if (context.Request.QueryString["id"] != null)
            regno = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/jpeg";
        Stream strm = ShowImage(regno);
        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);
        }
        context.Response.BinaryWrite(buffer);
    }

    public Stream ShowImage(int regno)
    {
        System.Data.DataTable dt = Student.getStudentData(regno.ToString());
        //if (dt.Rows.Count > 0)
        //{
            object imgP = dt.Rows[0]["imgattach_p"];
            
            try
            {
                return new MemoryStream((byte[])imgP);
            }
            catch
            {
                return null;
            }
        //}
        
    }
    
 
    public bool IsReusable {
        get {
            return false;
        }
    }

Just pass the particular row data to get image and get it in your handler.
 
Share this answer
 
v3
C#
var binatyDataFromDB;
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);

writer.Write(binatyDataFromDB);
writer.Flush();

Image image = Image.FromStream(srteam);


GDI+ has built-in supports for image format of BMP, GIF, JPEG, PNG, TIFF...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900