Click here to Skip to main content
Click here to Skip to main content

Image Handling In ASP.NET

By , 2 Feb 2012
 
A Technical Blog article. View entire blog here.

Contents

  • Introduction
  • Store Image
    • In Database
    • In Folder
  • Display Image in Image Control, GridView and DataList
    • From Database
    • From Folder
  • Creating Thumbnails
  • Adding Watermark Text on Image
  • Adding Image as Watermark

Introduction

In this article, I am going to explain how to handle images in ASP.NET. I have seen a lot of questions regarding "How to save and display image from database in ASP.NET" in different .NET discussing forums. I think it must be helpful for beginners to solve their problems regarding images in ASP.NET.

Store Images

We can store images in database and project folders. If it is in database, the datatype of image data is "image", now we can check the database design.

In Database

Here I used create a store procedure to save image in database.

CREATE PROCEDURE [dbo].[sp_UploadImage]
@imageData as image
AS
BEGIN
INSERT INTO Images (imageData) VALUES(@imageData)
END

Now we can look at how to save image in database. We need one FileUpload control to select file, and need to check file extension to verify uploading file is image or not. The below script function "valiadate();" checks the file is an image or not, i.e. we check the file extensions with JavaScript.

Javascript to check Upload file extension

<script language="javascript" type="text/javascript">
            function validate() {
                var result = false;
                var upfile = document.getElementById("FileUpload1").value;
                if (upfile != "") {
                    var accept = "png,gif,jpg,jpeg".split(',');
                    var getExtention = upfile.split('.');
                    var extention = getExtention[getExtention.length - 1];
                    for (i = 0; i < accept.length; i++) {
                        if (accept[i] == extention) {
                            result = true;
                            break;
                        }
                    }
                    if (!result) {
                        alert("allowed file extention are png,gif,jpg,jpeg");
                    }
                }
                else {
                    alert("select image to Upload");
                }
                return result;
            }
        
</script>

Now check the .aspx page:

 <asp:fileupload id="FileUpload1" runat="server">
    <asp:button id="btnUploadImage" onclick="btnUploadImage_Click" 
    onclientclick="return validate();" runat="server" text="Upload to DataBase">

Now the server side code. Read bytes value from FileUpload control and pass that value with stored procedure name into a HashTable. That hashtable sends to DataBaseHelper class file to save image in database.

 protected void btnUploadImage_Click(object sender, EventArgs e)
    {
        //server side checking
        if (FileUpload1.PostedFile.ContentType.ToLower().StartsWith("image") && 
        FileUpload1.HasFile)
        {
            Hashtable imageHash = new Hashtable();
            imageHash.Add("@imageData", FileUpload1.FileBytes);
            DataBaseHelper DBHelper = new DataBaseHelper();
            //storing image in to DataBase
            DBHelper.ExecuteNonQuery("sp_UploadImage", imageHash);
        }
    } 

Database with Image Data

In Folder

Saving folder is simple to compare saving in database. FileUpload control has SaveAs() method to save file. Here I save images in "savedImages" folder. We are not keeping any values in database. At the time of display image, we pick images from folder using DirectoryInfo and FileInfo Class or Directory.GetFiles method.

protected void btnUploadToFolder_Click(object sender, EventArgs e)
    {
        //save file in folder
        if (FileUpload1.PostedFile.ContentType.ToLower().StartsWith
                ("image") && FileUpload1.HasFile)
        {
            string savelocation = Server.MapPath("savedImages/");
            string fileExtention = System.IO.Path.GetExtension(FileUpload1.FileName);
            //creating filename to avoid file name conflicts.
            string fileName = Guid.NewGuid().ToString();
            //saving file in savedImage folder.
            string savePath = savelocation + fileName + fileExtention;
            FileUpload1.SaveAs(savePath);
        }
    }

Preview of saved images in folder

Display Images in Image Control, GridView and DataList

To display image from database is not as simple as displaying from folders because we previously saved image as byte in database.

From Database

To display image, we need to change byte data to Image; to convert byte data to image we need to use a separate page, here I am using a Generic Handler page to show image from database. In that Generic Handler page, we take image byte from database and render in that Handler page and set image controls src or ImageUrl to that Generic Handler page. For example, it work like this:

//from database
Image1.ImageUrl="Handler.aspx?id=1";
//from folder
Image1.ImageUrl="savedImages/ca34fa6c-8321-492c-938b-5413781bdcde.png";

Method 1 - Display image in Generic Handler page:

public void ProcessRequest (HttpContext context) {
        HttpRequest request = context.Request;
        if (!string.IsNullOrEmpty(request.QueryString["id"]))
        {
            //this hash table contain the SP parameter
            Hashtable hash = new Hashtable();
            hash.Add("@imageID", request.QueryString["id"]);
            DataBaseHelper DBHelper = new DataBaseHelper();

            //DBHelper.SQLExecuteNonQuery(procedure_name,command_parameters) 
            //return the object data.
            // casting return value to byte[]
            byte[] imageByte = (byte[])DBHelper.SQLExecuteNonQuery
            ("sp_getImage", hash);
            //creating object of image
            System.Drawing.Image b;
            //creating object of bitmap
            Bitmap bitMap = null;
            //checking byte[] 
            if (imageByte != null && imageByte.Length > 0)
            {
                //creating memoryStream object
                using (MemoryStream mm = new MemoryStream())
                {
                    //writing to memoryStream
                    mm.Write(imageByte, 0, imageByte.Length);
                    b = System.Drawing.Image.FromStream(mm);
                    bitMap = new System.Drawing.Bitmap(b, b.Width, b.Height);
                    //creating graphic object, to produce High Quality images.
                    using (Graphics g = Graphics.FromImage(bitMap))
                    {
                        g.InterpolationMode = 
                        System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.CompositingQuality = 
                        System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.DrawImage(bitMap, 0, 0, b.Width, b.Height);
                        g.Dispose(); b.Dispose(); mm.Dispose();
                        //changing content type of handler page
                        context.Response.ContentType = "image/jpeg";
                        //saving bitmap image
                        bitMap.Save(context.Response.OutputStream, 
                            System.Drawing.Imaging.ImageFormat.Jpeg);
                        bitMap.Dispose();
                    }
                }
            }
        }
    }

Method 2 - You can also use this code to render image in Handler page:

public void ProcessRequest (HttpContext context) {
        HttpRequest request = context.Request;
        if (!string.IsNullOrEmpty(request.QueryString["id"]))
        {
            //this hash table contain the SP parameter
            Hashtable hash = new Hashtable();
            hash.Add("@imageID", request.QueryString["id"]);
            DataBaseHelper DBHelper = new DataBaseHelper();

            //DBHelper.SQLExecuteNonQuery(procedure_name,command_parameters) 
            //return the object data.
            // casting return value to byte[]
            byte[] imageByte = (byte[])DBHelper.SQLExecuteNonQuery("sp_getImage", hash);
            //checking byte[] 
            if (imageByte != null && imageByte.Length > 0)
            {
                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite(imageByte);
            }
        }
    } 

Example of Handler page displaying image, and check the URL, it displays 3rd image from the database.

Stored procedure used to get Image:

CREATE PROCEDURE sp_getImage
@imageID as numeric
AS
BEGIN
SELECT imageData FROM Images WHERE imageId=@imageID
END 

I already said how to display image in Image control. Now we can check how to display in GridView Control form folders and Database. From Database. In the aspx page, I put a GridView and then set SqlDataSource, after that I add a Template column, then drag and drop an Image control in Template column and set ImageUrl of the image control using Image DataBinding.

Setting image URL

Source of GridView

Passing imageId to Handler.ashx page. It will display image as I said above.

Preview with HTML Source.

Displaying Image From Folder

You need to add a template column in GridView after that put one image control on template column, then set image controls DataImageUrlField from DataTable.

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false">
     <Columns>
         <asp:ImageField  DataImageUrlField="Image">
         </asp:ImageField>
     </Columns>
 </asp:GridView>

Server Side Code

 private void BindImage()
    {     
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Image", typeof(string)));
        DataRow dr;
        int i = 0;
  //fetching files from savedImages folder
        foreach (string file in Directory.GetFiles(Server.MapPath(@"savedImages\")))
        {
            dr = dt.NewRow();
            dt.Rows.Add(dr);
            dr["Image"] = "savedImages/" + System.IO.Path.GetFileName(file);
            i += 1;
        }
        GridView2.DataSource = dt;
        GridView2.DataBind();
    }

Now we can check how DataList works. Datalist is a more simple control than GridView. Here also, we call Database image with Generic Handler file Handler.ashx and pass "id" as QueryString. Handler file display image, and we point that image in to our DataList control.

<asp:DataList ID="DataList1" runat="server"
            RepeatColumns="3" RepeatDirection="Horizontal">
            <ItemTemplate>
                <table>
                    <tr>
                        <td valign="middle" align="center" 
            style="background-color:#cccccc;border:1px solid gray;
            width:150px;height:150px;"><%#DataBinder.Eval
            (Container.DataItem, "images") %></td>
                    </tr>
                </table>
            </ItemTemplate>
        </asp:DataList>
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            BindDataList();
    }
    private void BindDataList()
    {
        string sqlCmd = "SELECT imageid FROM Images";
        DataBaseHelper DBHelper = new DataBaseHelper();
        DataTable dt = DBHelper.GetTable(sqlCmd);
        //adding new column to display image
        DataColumn imageCol = new DataColumn("images", typeof(string));
        dt.Columns.Add(imageCol);
        
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i][imageCol] = string.Format
        ("<img src='Handler.ashx?id={0}' alt='' style='width:100px' />", 
            dt.Rows[i][0].ToString());
            }
        }
        DataList1.DataSource = dt;
        DataList1.DataBind();
    }

Preview of Images in DataList Control

Creating Thumbnails Image

To create a thumbnail, we need an image. We can pick image from FileUpload control, then we need to know dimension of image, i.e. [ Width x Height ]. Here I create a UI to handle this.

Check the UI:

To maintain aspect ratio of image with height and width, I use a class AspectRatio.cs. You can get the source code "Browse Code" or "Download Source" Section. Now we can look at the code of thumbnail creating section. As I said above, here I call a function to create thumbs. Let's look at this. The below method returns Bitmap image, I am saving that image in root folder.

 public Bitmap CreateThumbnail(byte[] imageByte, 
    bool maintainAspectRatio, int desiredWidth, int desiredHeight)
    {
        Bitmap bmp = null;
        try
        {
            MemoryStream memStream = new MemoryStream(imageByte);
            System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);

            if (maintainAspectRatio)
            {
                AspectRatio aspectRatio = new AspectRatio();
                aspectRatio.WidthAndHeight(img.Width, img.Height, 
            desiredWidth, desiredHeight);
                bmp = new Bitmap(img, aspectRatio.Width, aspectRatio.Height);
            }
            else
            {
                bmp = new Bitmap(img, desiredWidth, desiredHeight);
            }
            memStream.Dispose();
        }
        catch(Exception ex)
        {
            havException = true;
            ExceptionMessage = ex.Message;
        }
        return bmp;
    }

Server side code of "Create Thumbnail" Button. You can see this button in the above image. Here, I pass image byte[] to CreateThumbnail method. It returns Bitmap Image, and save that file in root folder.

 protected void btnCreateThumb_Click(object sender, EventArgs e)
    {
        int width = 0;
        int height = 0;
        byte[] image = FileUpload1.FileBytes;
        Int32.TryParse(txtDWidth.Text, out width);
        Int32.TryParse(txtDHeight.Text, out height);
        ImageHandler imageHandler = new ImageHandler();
        bool maintainAR = cbxAspectRation.Checked;
        //calling CreateThumbnail Method to create thumb images
        //it returns Bitmap Image. 
        Bitmap bmp = imageHandler.CreateThumbnail(image, maintainAR, width, height);
        if (bmp != null)
        {
            //creating a file name with guid.
            string fileName = Guid.NewGuid().ToString() + ".jpg";
            //saving in current root folder.
            bmp.Save(Server.MapPath(fileName));
            //set image controls ImageUrl to saved Image, 
            //this is to view the thumbnail image
            Image1.ImageUrl = fileName;
        }
        else
        {
            //exception part
            if (imageHandler.havException)
            {
                Response.Write(imageHandler.ExceptionMessage);
            }
        }
    }

You can check preview of Thumbnail, Height and Width of image with the help of Firebug console.

Creating Watermark Text on Image

Now we can discuss how to add Watermark on image. I think you know about Watermark. Here I call a method AddWatermarkText to add watermark on image. I pass image byte and watermark text to this method. The method is created on System.Drawing.Image object from MemoryStream. MemoryStream holds the image Byte. Using System.Drawing.SolidBrush and System.Drawing.Font, we create Text after that:

Graphics.DrawString(string s, Font font, Brush brush, PointF point);

We write text on Image. The below method is AddWatermarkText(byte[] imageByte,string textOnImage); you can check that.

public Image AddWatermarkText(byte[] imageByte,string textOnImage)
    {
        System.Drawing.Image img = null;
        try
        {
            MemoryStream memStream = new MemoryStream(imageByte);
            img = System.Drawing.Image.FromStream(memStream);
            Graphics g = System.Drawing.Graphics.FromImage(img);
            Font font = new Font("Aril", 30, FontStyle.Bold);

            SolidBrush solidBrush = new SolidBrush(Color.Red);
            Point point = new Point(img.Width / 3, img.Height / 2);
            g.DrawString(textOnImage, font, solidBrush, point);
            g.Save();

            memStream.Dispose();
            g.Dispose();
            solidBrush.Dispose();
            font.Dispose();
        }
        catch(Exception ex)
        {
            havException = true;
            ExceptionMessage = ex.Message;
        }
        return img;
    }

The above method returns Image. I am saving this image in root folder and display it using an Image control. You can check the UI of add Watermark Page and watermark on resultant Image.

Now we can check the code of Add Watermark button:

 protected void btnAddWaterMark_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            byte[] imgbyte = FileUpload1.FileBytes;
            //creating object of ImageHandler Class
            ImageHandler imageHandler = new ImageHandler();
            System.Drawing.Image imageWithWatermark = 
        imageHandler.AddWatermarkText(imgbyte, txtWaterMarkText.Text);
            if (imageWithWatermark != null)
            {
                //file name to save
                string saveFileName = Guid.NewGuid().ToString() + ".jpg";
                //saving image in current root location
                imageWithWatermark.Save(Server.MapPath(saveFileName));
                //displaying image file in a Image Control
                Image1.ImageUrl = saveFileName;
                imageWithWatermark.Dispose();
            }
            else
            {
                if (imageHandler.havException)
                {
                    Response.Write(imageHandler.ExceptionMessage);
                }
            }
        }
    }

Image as Watermark

In this section, I am explaining how to add Image as watermark. I think you have seen the same website with images. They have their log on image. We can check how to do something like that. First we need a logo image. Here I take CodeProject's logo image to explain this example. I save CodeProject logo image in watermarklogo folder.

I am embedding CodeProject logo image into an upload image, using Graphics.DrawImage(Image image, Point point); method. Here I add fading to logo image using TextureBrush.

 //add fading to logo image  using TextureBrush
        System.Drawing.Image waterMarkimage = System.Drawing.Image.FromFile
        (Server.MapPath("watermarklogo/CodeprojectLogo.jpg"));
        Graphics opacity = System.Drawing.Graphics.FromImage(waterMarkimage);
        Rectangle imageRect = new Rectangle(0, 0, waterMarkimage.Width, 
                waterMarkimage.Height);
        Brush brush = new TextureBrush(waterMarkimage, imageRect);
        opacity.FillRectangle(brush, imageRect);
        opacity.Save();

Check the sample image:

Check the source code:

protected void btnAddImageAsWaterMark_Click(object sender, EventArgs e)
    {
        byte[] imageByte = FileUpload1.FileBytes;
        MemoryStream memStream = new MemoryStream(imageByte);
        System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);

        //add fading to logo image  using TextureBrush
        System.Drawing.Image waterMarkimage = System.Drawing.Image.FromFile
        (Server.MapPath("watermarklogo/CodeprojectLogo.jpg"));
        Graphics opacity = System.Drawing.Graphics.FromImage(waterMarkimage);
        Rectangle imageRect = new Rectangle(0, 0, waterMarkimage.Width, 
                waterMarkimage.Height);
        Brush brush = new TextureBrush(waterMarkimage, imageRect);
        opacity.FillRectangle(brush, imageRect);
        opacity.Save();
       
        Graphics g = System.Drawing.Graphics.FromImage(img);
        Point point = new Point(img.Width / 3, img.Height / 2);
        g.DrawImage(waterMarkimage, point);
        string filename = Guid.NewGuid().ToString() + ".jpg";
        img.Save(Server.MapPath(filename));
        
        opacity.Dispose();
        memStream.Dispose();
        g.Dispose();
        waterMarkimage.Dispose();
        img.Dispose();

        Image1.ImageUrl = filename;
    } 

License

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

About the Author

raju melveetilpurayil
United Kingdom United Kingdom
Member
Microsoft Certified Professional Developer.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionI also want to get other fields with ImagememberMustafaIqbal30 Oct '12 - 9:29 
Mr. raju melveetilpurayil
 
Please tell me, What can I do if I want to get other data fields with image from SQL to Listview, like Image_Name etc. Thanks, your article is great and helpful for me, I vote for 5 Smile | :)
QuestionNULL image in some recordsmemberZaiem27 Sep '12 - 10:47 
I have a database with (name, image) where the image in some records are NULL
I made an imagehandler to display images on the gridview.
I am getting an exception
using (con)
{
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
 
//// Unable to cast object of type 'System.DBNull' to type 'System.Byte[]
context.Response.BinaryWrite((byte[])dReader["Photo"]);
//// Unable to cast object of type 'System.DBNull' to type 'System.Byte[]
 
dReader.Close();
}
How can I make the handler dispaly images when availble on the grid, and pass exception if image was NULL on someother record.
GeneralImage HandelmemberManohar Khillare11 Jun '12 - 4:00 
Great Article Its Really Help for me I give u vote 5 out of 5

GeneralRe: Image Handelmemberraju melveetilpurayil13 Jun '12 - 4:58 
Thanks mate..
Generaldatabasehelpermemberdineshdena1 Jun '12 - 0:31 
what is databasehelper???
GeneralRe: databasehelpermemberraju melveetilpurayil13 Jun '12 - 4:57 
Its a helper class for accessing database. for example, you do not want to call Con.Open() and Con.Close() in every page.Cool | :cool:
QuestionCode listing mismatchmemberNitinSingh3 May '12 - 21:12 
In description of image handler, the url set to image control is "Handler.aspx" instead of "Handler.ashx" whereas in screenshot of page view, its Handler.aspx.
AnswerRe: Code listing mismatchmemberraju melveetilpurayil5 Jul '12 - 11:23 
I think, You said about below line. if its I just wrote that as an example.
Image1.ImageUrl="Handler.aspx?id=1";
anyway sorry for the mistake. Thanks
QuestionMy vote of 5memberegenis2 May '12 - 18:30 
Great article! Well done.
AnswerRe: My vote of 5memberraju melveetilpurayil13 Jun '12 - 4:59 
Thank you
QuestionCALLING GENERIC HANDLER FROM CONTENT PAGE ASP.NETmembergitcue1 May '12 - 2:40 
Using ASP.Net, i'hv developed a master page with a form.
Now, i developed a content page with a form. On submit of content page form button i wana call a generic handler. How can i do this???? Wen a simply do this handler is not called.
I cant pass form action inn master page as this affecting other pages.
Wen i simply developed a page without dis master page den code workin fine.
QuestionRetrive the Image from Image ControlmemberGeoNav20 Apr '12 - 23:03 
Hi,
I am displaying the picture on an image control using the generic handler. Now, I want to retrieve this image at a later stage for storage in the SQL DB. How to get the image from the image control?
GeneralWell done.membersamip shrestha3 Apr '12 - 20:06 
Thank you so much for the nice article...Nice and easy to understand.
GeneralRe: Well done.memberraju melveetilpurayil14 Aug '12 - 23:09 
Welcome
My Mind is the Devil's Workshop.

GeneralMy vote of 5memberMember 87648143 Apr '12 - 7:03 
Very Good Article. Congratulations.
GeneralRe: My vote of 5memberraju melveetilpurayil14 Aug '12 - 23:09 
Thanks for the comment.
My Mind is the Devil's Workshop.

GeneralMy vote of 5membersau731 Apr '12 - 22:11 
this is an amazing and most helpful for image handling...
thanks a lot.
GeneralRe: My vote of 5memberraju melveetilpurayil14 Aug '12 - 23:08 
Welcome
My Mind is the Devil's Workshop.

QuestionImage Handling In ASP.NETmemberfahad4512 Feb '12 - 8:38 
Hello
Thank you for this great one.
I get an error (GDI+ error) when i run it over a network, but it works fine in localhost.
is there any work around this problem?
 
Thanks.
fahad

AnswerRe: Image Handling In ASP.NETmemberraju melveetilpurayil14 Aug '12 - 23:08 
please update me with error details, let me look on it first.
 
Thanks
My Mind is the Devil's Workshop.

QuestionMy Vote of 5memberRoberto Ferraris7 Feb '12 - 21:01 
Thanks.
A single remark: in SQL Server it's better to use varbinary(max) instead of image.
Image is from earlier versions (MSDN: Using Large-Value Data Types)
AnswerRe: My Vote of 5memberraju melveetilpurayil8 Feb '12 - 1:02 
Thanks man Thumbs Up | :thumbsup:
My Mind is the Devil's Workshop.

GeneralMy vote of 5memberDr Bob7 Feb '12 - 8:43 
Very nice work!
GeneralRe: My vote of 5memberraju melveetilpurayil8 Feb '12 - 1:00 
Thanks Mate Thumbs Up | :thumbsup:
My Mind is the Devil's Workshop.

QuestionWmembercyrusholiday7 Feb '12 - 0:16 
hi,
image handling concepts its important and lot of sense,
thanks for sharing...
regards,
cyrus holiday
www.cyrusholiday.info
AnswerRe: Wmemberraju melveetilpurayil8 Feb '12 - 0:59 
Thank you
My Mind is the Devil's Workshop.

Questionerrormembersaad hussain895 Feb '12 - 6:35 
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
AnswerRe: errormemberraju melveetilpurayil8 Feb '12 - 1:01 
thanks for the comment,
Let me check I will update this post...
My Mind is the Devil's Workshop.

AnswerRe: errormemberSimon_Whitehead8 Feb '12 - 1:05 
Your error is because it is connecting to a local SQL Server Express instance on the author's computer. You must change the "sqlCon" value in the web.config to point to a database on your machine/hosting for the examples to work. Remember that the database must have the same structure as the ones in the article.
If you don't succeed, redefine success!

GeneralRe: errormemberraju melveetilpurayil8 Feb '12 - 1:52 
thanks for the help Smile | :) Thumbs Up | :thumbsup: I am in office, I cant open CP all time.
QuestionPerhaps streaming an image is better?memberSimon_Whitehead2 Feb '12 - 13:16 
Hello,
 
I find streaming can lower the memory usage of the Application Pool, purely because you're avoiding any objects being placed on the Large Object Heap. You can accomplish this with the GetBytes method of the SqlDataReader: (table structure is 2 columns, first column binary, second is varchar)
 
SqlDataReader dbReader = sqlCommand.ExecuteReader();
 
byte[] buff = new byte[4096];
int bufferSize = buff.Length;
long startIndex = 0;
long retVal = 0;
 
if (dbReader.HasRows)
{
    dbReader.Read();
    retVal = dbReader.GetBytes(0, startIndex, buff, 0, bufferSize);
    while (retVal == bufferSize)
    {
        Response.OutputStream.Write(buff, 0, bufferSize);
        Response.OutputStream.Flush();
 
        startIndex += bufferSize;
        retVal = dbReader.GetBytes(0, startIndex, buff, 0, bufferSize);
    }
}
 
Response.ContentType = dbReader[1] as string; // mime-type is stored in the table too
Response.OutputStream.Write(buff, 0, bufferSize); // write the final read operation to the response
Response.OutputStream.Flush();
 
sqlConnection.Close();
 
Response.Flush();
The above is just an example.
 
The performance becomes apparent on a website with lots of images stored in a database and many concurrent users. Remembering that the LOH is capped at ~85kb.. most of, if not all of your images will actually exceed byte[85000].
 
Again, this is fine for a small website that handles few users.. but it can become a big issue when you've managed to snag a few thousand to your website at once (w3wp memory usage goes through the roof as it allocates more and more memory).
 
Maybe you can include this in your article?
If you don't succeed, redefine success!

AnswerRe: Perhaps streaming an image is better?memberraju melveetilpurayil8 Feb '12 - 0:59 
Thanks mate.. Its already Included by your comment. Thumbs Up | :thumbsup:
When I edit this article I will consider your suggestion ..
QuestionCan't download the source code of this articlememberMember 15705381 Feb '12 - 14:27 
WOuld apprecaite if you can make source code available
AnswerRe: Can't download the source code of this articlememberraju melveetilpurayil2 Feb '12 - 11:42 
Apologies..
Sorry for the trouble.. updated the article with source code. you can download from download link. Thanks you webmaster [Deeksha Shenoy] for the update.Thumbs Up | :thumbsup:
void raju(){ return error Wink | ;) }

GeneralMy vote of 5memberkiran dangar2 Oct '11 - 22:57 
great
GeneralRe: My vote of 5memberraju melveetilpurayil3 Oct '11 - 3:10 
Thanks
My Mind is the Devil's Workshop.

GeneralMy vote of 1memberambujs3 Apr '11 - 4:48 
the database is not there in the zip folder ..
GeneralRe: My vote of 1memberFabio Franco12 Apr '11 - 3:44 
That's hardly a reason to vote 1. This doesn't mean the article isn't well written or useful. Instead, you could simply notify the author and I'm sure he'd gladly do that.
 
Besides, what's the problem for you to create a table in the database, he's already describing it and with pictures.
You should reconsider your vote
GeneralRe: My vote of 1membersotiris krontiris6 Feb '12 - 21:05 
I totally agree with you. This a very nice article and because it just doesn't give you a hard copy of the database is not a reason to vote 1. I was looking for something similar a few months ago and believe me, this article is well written and useful.
GeneralMy vote of 5memberE$w@r15 Mar '11 - 9:11 
Nice article
GeneralRe: My vote of 5member[raju.m][makhaai]15 Mar '11 - 12:04 
thank you
My Mind is the Devil's Workshop.

GeneralMy vote of 5memberDilip Baboo17 Jan '11 - 6:59 
Awesome tutorial for image rendering from DB & File Folder.
GeneralRe: My vote of 5member[raju.m][makhaai]24 Jan '11 - 7:12 
thank for your comment
My Mind is the Devil's Workshop.

GeneralMy Vote of 5memberRaviRanjankr21 Dec '10 - 4:16 
Great work.
Excellent Article, Very useful for beginners
GeneralRe: My Vote of 5member[raju.m][makhaai]21 Dec '10 - 12:58 
Thank you
My Mind is the Devil's Workshop.

Generalgood onememberPranay Rana14 Dec '10 - 23:50 
good one
For any question : http://pranayamr.blogspot.com/
 
vote my article :

Learn SQL to LINQ ( Visual Representation )


Calling WCF Services using jQuery

GeneralRe: good onemember[raju.m][makhaai]18 Dec '10 - 12:45 
thank you very much
My Mind is the Devil's Workshop.

GeneralMy vote of 5memberSChristmas14 Dec '10 - 9:56 
you made lots of efforts to write this artcle. I find all types of image handling here. thanks for sharing. worth a 5!
GeneralRe: My vote of 5member[raju.m][makhaai]18 Dec '10 - 12:46 
Thanks manThumbs Up | :thumbsup:
My Mind is the Devil's Workshop.

GeneralMy vote of 5memberAbhinav S11 Dec '10 - 4:53 
Good article.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 2 Feb 2012
Article Copyright 2010 by raju melveetilpurayil
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid