CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Eric Wise

Business & .NET

Images, Thumbnails, SQL Server, and ASP .NET - Level 200

Ok, it's been a bit of time since I posted some technical content.  I seem to be the only codebetter blogger who has big business aspirations and is launching a real ISV so I've been trying to mix that content into the Codebetter feed for those of you who have similar aspirations.  I think it's time to get back to some technical content though.

Using SQL Server to manage images (or other files) is a frequently asked question of mine.  I have come across several clients in my consulting career where they were simply dumping the files into a physical directory on the webserver.  In the end, this is pretty sloppy and difficult to manage especially if for some reason you want to reorganize the data.

In this article I will show you the Easy Assets .NET method of handling image uploads.  The application allows clients to store images of their assets, mostly for insurance purposes.  I had a few goals for this section of the application as follows:

  1. Store images in sql server for easy management on my end.
  2. Automatically compress images so I don't have to worry about disk space usage or demand that my users compress it themselves which can be hard for a user without computer savvy (once again, EASY assets .net)
  3. Generate thumbnails for display in a list.

Step 1: Configuring SQL Server

First thing we must do is set up a SQL Server table to handle the data.  SQL Server has a handy image field to handle this type of thing.  Here's the table we'll be using in the example:

CREATE TABLE [dbo].[AssetImages] (
    [AssetImageID] [int] IDENTITY (1, 1) NOT NULL ,
    [AssetID] [int] NOT NULL ,
    [FileData] [image] NOT NULL ,
    [FileName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    [FileSize] [bigint] NOT NULL ,
    [ContentType] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
    [Thumbnail] [image] NOT NULL ,
    [LastEditUser] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [LastEditDateTime] [datetime] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

The main image will be stored in the FileData field and the thumbnail image will be stored in the Thumbnail field.

 

Step 2: Compressing the image

To compress the image, I used the handy tool I mentioned in this post.  You simply register the dll, and drag and drop the compressor tool onto the page.  The following code uploads an image from the html file upload object, compresses it, and then generates a thumbnail.  It uses my domain pattern, like all pages in Easy Assets .NET.

    Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        Try
            Dim upfile As HttpPostedFile = UploadFile.PostedFile
            ' Make sure there's actually content uploaded
 
            If upfile.ContentLength <> Nothing Then
                Dim myData() As Byte
                Dim stream As New MemoryStream
                Dim assetImage As New EasyAssets.DAC.AssetImage
 
                myData = ImageOptimizer1.Optimize(upfile)
                assetImage.FileSize = Convert.ToInt32(myData.Length / 1000)
 
                Dim i As Integer = InStrRev(upfile.FileName.Trim, "\")
                If i = 0 Then
                    assetImage.FileName = upfile.FileName.Trim
                Else
                    assetImage.FileName = Right(upfile.FileName.Trim, Len(upfile.FileName.Trim) - i)
                End If
 
                assetImage.AssetID = Convert.ToInt32(Request.QueryString("AID"))
                assetImage.FileData = myData
                assetImage.ContentType = upfile.ContentType
 
                Dim thumbnail As Bitmap = CreateThumbNail(New Bitmap(upfile.InputStream, False), 120, 120)
 
                thumbnail.Save(stream, ImageFormat.Jpeg)
                assetImage.Thumbnail = stream.GetBuffer()
 
                DomainManager.Save(assetImage)
                BindDataGrid()
            End If
        Catch ex As Exception
            WriteMessage(ex.Message, True)
        End Try
    End Sub

Few things to note:

  1. Filesize / 1000... default is bytes, I convert it to kilobytes.
  2. Bitmaps and memory streams are pretty cool, I know that the bitmap has a thumbnail creation method on it but I've heard that it doesn't do a nice job.  I found the following code on a MVP's site, sorry to whoever it was, I cleared my history and lost your blog.  Contact me and I'll give you proper credit.
    Private Function CreateThumbNail(ByVal postedFile As Bitmap, ByVal width As Integer, ByVal height As Integer) As Bitmap
        Dim bmpOut As System.Drawing.Bitmap
        Dim Format As ImageFormat = postedFile.RawFormat
        Dim Ratio As Decimal
        Dim NewWidth As Integer
        Dim NewHeight As Integer
 
        '*** If the image is smaller than a thumbnail just return it
        If postedFile.Width < width AndAlso postedFile.Height < height Then
            Return postedFile
        End If
 
        If (postedFile.Width > postedFile.Height) Then
            Ratio = Convert.ToDecimal(width / postedFile.Width)
            NewWidth = width
 
            Dim Temp As Decimal = postedFile.Height * Ratio
            NewHeight = Convert.ToInt32(Temp)
        Else
            Ratio = Convert.ToDecimal(height / postedFile.Height)
            NewHeight = height
 
            Dim Temp As Decimal = postedFile.Width * Ratio
            NewWidth = Convert.ToInt32(Temp)
        End If
 
        bmpOut = New Bitmap(NewWidth, NewHeight)
 
        Dim g As Graphics = Graphics.FromImage(bmpOut)
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
        g.FillRectangle(Brushes.White, 0, 0, NewWidth, NewHeight)
        g.DrawImage(postedFile, 0, 0, NewWidth, NewHeight)
 
        postedFile.Dispose()
 
        Return bmpOut
    End Function

 

Step 3: Binding thumbnails to a datagrid

Now, by default, you can't really show image data from sql server into a datagrid, so we have to sort of "trick" ASP .NET into inserting an image into the grid.  We do this by calling a special aspx page into the template column of the grid.  Here's how it works:

First, set up the template column of the grid as such:

Notice the call to the two pages, on click of the thumbnail I want to show them the full-size version of the photo in a popup window.  The thumbnail is bound to a function called "formaturl" that takes the id of the image as a parameter.  Let's take a look at this function:

    Protected Function FormatURL(ByVal imageID As Integer) As String
        Return ("AssetShowThumb.aspx?id=" & imageID.ToString())
    End Function

So basically we have told asp.net that the source of this image is the results of the AssetShowThumb.aspx.  But what does this page do?  Let's take a look:

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not Page.IsPostBack Then
            Dim assetImg As New EasyAssets.DAC.AssetImage(Convert.ToInt32(Request.QueryString("ID")))
            assetImg = DirectCast(DomainManager.Load(assetImg), EasyAssets.DAC.AssetImage)
 
            Response.ContentType = "Image/JPEG"
            Response.BinaryWrite(assetImg.Thumbnail)
        End If
    End Sub

So all we've done is load the image record, set the content type to jpeg (I force all saves in the above function to be jpegs), and binary write the image data.  We end up with a display like this:

And an original image (on click of thumb) like this:

And oh how I wish this picture, from my hawaii trip, was actually an asset of mine. =)



Comments

Sahil Malik said:

Since most of your audience are computer geeks, how about an english friendly, non-mba description of what

"Asset Management" is .. and why should I care?
# May 15, 2005 10:53 PM

Jeffrey Palermo said:

I've considered doing a photo album this way, but the main drawback is the size it makes the database. I have about 4GB of images. Do I really want that much in my database just for images. That also makes the bandwidth between web and db server highly used. Perhaps it's no big deal, but to date I've kept my photos on the web server. Please post if you find no issues with the size of the data in the database when you have _lots_ of pictures there.
# May 16, 2005 6:26 AM

Eric Wise said:

Sahil asks on this post:
&quot;Since most of your audience are computer geeks, how about an english friendly,...
# May 16, 2005 7:02 AM

Eric Wise said:

Jeff,

With the compression tool I referenced, the original image shown was over 2MB, now it's 165KB.

Having many large files would definately cause a performance issue, but with compression and the fact that it will probably be rare to have more than 2-3 pictures of an asset I'm not all that concerned about it.
# May 16, 2005 7:05 AM

Christopher Steen said:

Link Listing - May 20, 2005
# May 20, 2005 9:50 PM

Finger said:

Hi Eric, I have successfully reproduced about 95% of this article. However when it comes to displaying the picture i am a little confused. I am using a DataSet as my datasource and i don't know what to cast it as to make the image appear. Here is my code in the pageload event on the showimage.aspx page. I have tried to cast it as a byte[]. but unsuccessfully. Any thoughts would be appreciated.

DataView dvStaff = new DataView();
dvStaff.Table = dsData.myStaff;
dvStaff.RowFilter = "StaffKey='" + Request.QueryString["id"].ToString();
byte[] temp = (byte[])dvStaff[0]["FileData"];
Response.ContentType="image/gif";
Response.OutputStream.Write(temp,0,temp.Length);
# June 20, 2005 5:09 AM

Eric Wise said:

Try replacing:

byte[] temp = (byte[])dvStaff[0]["FileData"];
Response.ContentType="image/gif";
Response.OutputStream.Write(temp,0,temp.Length);

With:
byte[] temp = (byte[])dvStaff[0]["FileData"];
Response.ContentType="image/gif";
Response.BinaryWrite(temp)
# June 20, 2005 9:53 AM

Eric Wise said:

On a side note, on the show image page you should only load the record that has the photo (use a datareader instead of a dataset). It appears in your code sample that you're populating a datareader with a ton of rows you don't need. Due to the size of images this could end up being a pretty hefty performance hit for you.
# June 20, 2005 9:55 AM

Rich said:

I'm a bit of a beginner and need help understanding or working out these errors, Your site is very helpful as I have been googling for hours and the only outcome I have found besides paying for a asp Uploading images to a database is your method, :) Okay I think i need some inherits at the beg of my page because I have used your code and don't know how to modify it to suit my needs so it gives me the following blue underline of death, Not being able to recognize these things,

Does not recognize these items in the page load
EasyAssets.DAC.AssetImage
DomainManager

Does not recognize these in buttonUPdate

UploadFile
MemoryStream
EasyAssets.DAC.AssetImage
ImageFormat.Jpeg
DomainManager
WriteMessage

Does not recognize t his in Thumbnail
ImageFormat

Hopefully Understanding these errors will also help all those other beginners out their that find use of your code, Thanks
# June 24, 2005 12:34 PM

Johan Smit said:

I think you would do all visitors a big favour by adding the namespace references along with your sample code....
# July 8, 2005 5:58 AM

Eric Wise said:

Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging
# July 9, 2005 6:35 AM

Gopal said:

I have tried a lot to run your sample but allways i have failed,
if you can you send me working code at pandagopal@yahoo.com that would be a great help.
# October 4, 2005 4:37 PM

Sandi L. said:

Thanks for posting this sample code, Eric. It has been a great help. I had been able to save my pics in SQL but was missing the compress step. Leads to major download frustration. Thanks a whole bunch. ... Just a brief note for Sahilmalik: "Asset Management keeps the world going round. It's how you keep track of who has what when."
# October 5, 2005 5:25 PM

zioturo said:

# November 2, 2005 12:56 PM

Gulshan said:

HI Eric Thanks For Posted this Sample


But I am not able to run this code
How I can add
EasyAssets.DAC.AssetImage
DomainManager


and What is use for this Classes


I am required Your Help
# December 26, 2005 1:05 PM

Eric Wise said:

Those two classes are custom classes used for database access in the asset management application I was using this code snippet in.

You should replace them with your own database access objects specific to your application.
# December 27, 2005 1:11 PM

Long said:

Hi, Eric,
If I want to set up a webservice that can draw a circle (image) then return the image as byte[], how can I do it?

Thanks,
Long
# May 5, 2006 7:11 PM

Eric Wise said:

Long,

That's a good question.  The answer lies in the System.Drawing class but to be honest I have never used the namespace.  Searching on that namespace should help you find the resources you need though!
# May 9, 2006 7:52 AM

Tom said:

Hi Eric,

Great! Thanks a lot for sharing your knowledge

-Tom from Belgium
# May 15, 2006 6:21 AM

Lakshman said:

thanks for giving information.really so good
# June 16, 2006 2:24 AM

Preethi said:

Hello Eric,

Nice Article!
where is the dll file

thanks for sharing your knowledge.
# July 14, 2006 6:04 AM

suniti said:

thanx man, you made my day................ i needed this code badly.
thanx a bunch.
# July 19, 2006 3:45 PM

rohan said:

hi .this  is  very good .
can you  u give me code in  c#.net.
including html
rohan992003@yahoo.co.in
# August 9, 2006 9:54 AM

sunmorgus said:

I would very much like to go over the source code for this. Could you pleas email it to me, as I do not see a link on the page where I can download it? sunmorgus@gmail.com
Thanks!
# August 18, 2006 1:08 PM

manimegalai said:

very useful article

 thankx to all

# August 31, 2006 1:18 AM

Manisha Kadam said:

it will work nice and helpful

but can u tell me what is "EasyAssets.DAC.AssetImage"

how can i get this

pls replay urgently

# September 19, 2006 5:41 AM

Dave said:

Thanks, I liked the tutorial. keep up the cool work

Best Regards

# October 11, 2006 11:41 PM

Etienne said:

Thanks man, you're a star!

This code is quality and it works very well :o)

Etienne Lambert

Another happy programmer.

# November 2, 2006 10:48 AM

Khurram said:

Hi great stuff but the compressing tools are all payed providing just free trial versions :(

Khurram

# November 30, 2006 3:28 AM

Jan said:

Hi, thanks for this article. I am 'porting'it to C3 and have a question:

1. is the source code donwnloadable for the comlpete worling example

2. in the function CreateThumbNail the ratio is calculated as an integer division. this means that for example that the ratio is 0 when the heigth of is 120 and the postedFile.Height = 250. the ratio of zero is giving an exception while creating the new bitmap since one of its dimensions is 0.

Can you comment on that?

Thanks,

Jan

# December 6, 2006 7:02 AM

suresh said:

hi,

fine i need

how to show the image from sql in asp.net using c#

send a code to happysuresh@hotmail.com

# January 17, 2007 11:17 PM

Craig Mellon said:

Hi,

I read your article and the mention of the Bitmap.CreateThumbnail function.  It does indeed sometimes distort the images when using this method, however there is a neat trick you can do which doesn;t distort the image.

     ' Force image to recreate thumbnail so not to distort image

     fullSizeImg.RotateFlip(Drawing.RotateFlipType.Rotate180FlipNone)

     fullSizeImg.RotateFlip(Drawing.RotateFlipType.Rotate180FlipNone)

If you do tis just before calling the GetThumbnailImage function the thumbnail will not be distorted.  Just thought I would mention it.

# February 1, 2007 6:40 PM

khubeb` said:

sir,

i want to save the image of person  in sqlserver and whenever required retrieve it.

# March 7, 2007 12:42 AM

Kalyan said:

Hi,

  Im using the GDI and Response.OutputStream to generate the bitmap in aspx page. After doing the above said thing im giving that aspx page as imageURl to ImageButton which is the  item of the datalist in another page. By doing this everthing working good and im displaying 20-30 images per page. The problem is that whenever i refresh the browser intially it showing blank page for while and then images are displayed. It woould be appreciable if given suggestions.

# March 16, 2007 8:35 AM

pradyuman said:

hi eric,

That's such a nice article. i want to do the same thing but it's not working using this code. some error occurs.

Can u mail me the working code of the same.(pmjadeja.it@gmail.com)

Thanks.

# April 5, 2007 12:50 AM

George Evans said:

Hi

Awesome site. Thanks so much for putting it up Eric. Like other that have posted, I would like to retrieve the image from SQL Server. I have clicked on the links but they don't load. Can someone tell me how?

Thanks George

# April 9, 2007 2:50 AM

George Evans said:

Sorry, Email is evansgeorge2@hotmail.com

# April 9, 2007 2:53 AM

MMDG said:

Great stuff, but is there a download for this anywhere?

I read people asking for code but no one saying they recieved it.

Thanks

# June 15, 2007 11:22 AM

Chuck Mahenski said:

Good write up! Based on some of the feedback it looks like some folks were not able to get this working. I thought I would add a sample with everything in one method for ease.

Note: get the Optimizer dll from www.imageoptimizer.net/pages

In Visual Studio 'right click' the tool bar tab and select 'Choose Item'  to add the control. Drag and drop this on a page.

Create a reference to the resource dll. (right click the projects name and sellect add reference.)

This example does not implement the thumbnail piece, this just save an optimized image to the DB and the retrieves it back and displays it.

Note I use a stored procedure for saving and I get the scope_identity so I know the ID of the file I just saved.

The stored procedure is..

ALTER PROCEDURE dbo.DHQ_InsertImage_sp

(

@FileData image,

@FileName nvarchar(50),

@FileSize bigint,

@ContentType nvarchar(50)

)

AS

INSERT INTO AssetImages(FileData, FileName, FileSize, ContentType)

          VALUES(@FileData,@FileName,@FileSize,@ContentType)

    RETURN  Scope_Identity()

The page code is......

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class DHQImage : System.Web.UI.UserControl

{

   SqlCommand cmdGet;

   SqlConnection connect;

   SqlDataAdapter adapter;

   struct fileDetail

   {

       public Byte[] FileData;

       public string FileName;

       public Int32 FileSize;

       public string ContentType;

       public Byte[] Thumbnail;

   }

   protected void Page_Load(object sender, EventArgs e)

   {

   }

   protected void lnkUpImg_Click(object sender, EventArgs e)

   {

       if (this.FileUpload1.HasFile)

       {

           HttpPostedFile pf = this.FileUpload1.PostedFile;

           if (pf.ContentLength != 0)

           {

               fileDetail container = new fileDetail();

               container.FileData = this.imgOpt.Optimize(pf);

               container.FileSize = Convert.ToInt32(container.FileData.Length / 1000);

               container.FileName = pf.FileName;

               container.ContentType = pf.ContentType;

               // cmdSave = new System.Data.SqlClient.SqlCommand();

               adapter = new SqlDataAdapter();

               connect = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());

               connect.Open();

               adapter.InsertCommand = new SqlCommand("DHQ_InsertImage_sp", connect);

               adapter.InsertCommand.CommandType = CommandType.StoredProcedure;

               adapter.InsertCommand.Parameters.Add("@FileData", System.Data.SqlDbType.Image);

               adapter.InsertCommand.Parameters["@FileData"].Value = container.FileData;

               adapter.InsertCommand.Parameters.Add("@FileName", System.Data.SqlDbType.NVarChar, 50);

               adapter.InsertCommand.Parameters["@FileName"].Value = container.FileName;

               adapter.InsertCommand.Parameters.Add("@FileSize", System.Data.SqlDbType.BigInt, 8);

               adapter.InsertCommand.Parameters["@FileSize"].Value = container.FileSize;

               adapter.InsertCommand.Parameters.Add("@ContentType", System.Data.SqlDbType.NVarChar, 50);

               adapter.InsertCommand.Parameters["@ContentType"].Value = container.ContentType;

               adapter.InsertCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int);

               adapter.InsertCommand.Parameters["@ID"].Direction = ParameterDirection.ReturnValue;

               //int iresult = adapter.InsertCommand.ExecuteNonQuery();

               SqlDataReader read = adapter.InsertCommand.ExecuteReader(CommandBehavior.SingleResult);

               int resultID = Convert.ToInt32(adapter.InsertCommand.Parameters["@ID"].Value);

               read.Close();

               connect.Close();

               cmdGet = new System.Data.SqlClient.SqlCommand();

               cmdGet.CommandText = "SELECT FileData FROM AssetImages WHERE AssetImageID = " + resultID + "";

               connect.Open();

               cmdGet.Connection = connect;

               byte[] GetImg = (byte[])cmdGet.ExecuteScalar();

               connect.Close();

               connect.Dispose();

               if (GetImg != null)

               {

                   Response.ContentType = "image/jpeg";

                   Response.Expires = 0;

                   Response.Buffer = true;

                   Response.Clear();

                   Response.BinaryWrite(GetImg);

                   Response.End();

               }

           }

       }

   }

}

# June 21, 2007 6:24 PM

Chuck Mahenski said:

One last thing....

The connection string is in the Web.Config file within the configuration element.

<connectionStrings>

<add name="conn" connectionString="Data Source=[Your DB Server];Initial Catalog=[Db Name];Integrated Security=True" providerName="System.Data.SqlClient"/>

</connectionStrings>

That's about it really...you could probably cut and paste this example.

# June 21, 2007 6:31 PM

Ed Dror said:

After 3 hours of trying to make things happend

I gave up It dosen't work for me

edd@andrewlauren.com

I wish I can download the code for this blog

# June 22, 2007 12:02 PM

Chuck Mahenski said:

To get the images in SQL server you just declare a Byte array:

public Byte[] FileData;

After adding the 'Optimizer' dll to your reference and tools, you drag it to the form and change a couple properties.

Get the file from the file upload control and validate its length:

HttpPostedFile pf = this.FileUpload1.PostedFile;

if (pf.ContentLength != 0)

Pass the posted file to the optimizer....

FileData = this.imgOpt.Optimize(pf);

Get all info you feel you need (like name, file size, content type, etc..)

Create your Sql command, connection, command text or stored procedure. Execute to save. The keys are:

- Get the file

- You pass the file object to the optimizer

- You must save the image in Bytes (or convert the size to KB size/1000) and save the Byte stream to a Byte array data type.

- This gets saved into a data table field of type image (for Sql server)

When you want to display the image again....

- Create an aspx form and place the logic to get and display the image

Example:

 protected void Page_Load(object sender, EventArgs e)

   {

       int IDImage = Convert.ToInt32(Request.QueryString["ID"]);

       try

       {

           if (connect.State != ConnectionState.Open)

               connect.Open();

           if (IDImage > 0)

           {

               cmdGet = new System.Data.SqlClient.SqlCommand();

               cmdGet.CommandText = "SELECT FileData FROM AssetImages WHERE AssetImageID = " + IDImage + "";

               cmdGet.Connection = connect;

               GetImg = (byte[])cmdGet.ExecuteScalar();

               Response.ContentType = "image/jpeg";

               Response.Expires = 0;

               Response.Buffer = true;

               Response.Clear();

               Response.BinaryWrite(GetImg);

               //Response.End();

              HttpContext.Current.ApplicationInstance.CompleteRequest();

           }

       }

       catch (Exception ex) {  }

       finally

       {

           connect.Close();

       }

   }

NOTE: I made this as trim as I could. Also, I dont use Response.End(); because it causes false errors. Use HttpContext.Current.ApplicationInstance.CompleteRequest() instead.

Now....this page will get called from any other page where you want the image to be displayed. You can do this in a Datalist, DataGrid, etc...control or just and asp Image control.

Datalist example:

   <form id="form1" runat="server">

       <asp:DataList ID="DataList1" runat="server" Width="550px" DataSourceID="SqlDataSource1">

       <ItemTemplate>

       <asp:Image ID="img" Width="550" ImageUrl='<%# FormatURL(DataBinder.Eval(Container.DataItem, "AssetImageID")) %>' Runat=server />

       </ItemTemplate>

       </asp:DataList><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:conn %>"

           SelectCommand="SELECT [AssetImageID] FROM [AssetImages]"></asp:SqlDataSource>

   </form>

You can see this calls the method in the code behind...

   public string FormatURL(object _id)

   {

       int num = Convert.ToInt32(_id);

       return ("~/GetImage.aspx?id=" + _id);

   }

...and GetImage.aspx is the page you created to get and display the image.

Note: Create a data source and bind your control. specify the name of the data source and the field in your table to evaluate. (Container.DataItem, "AssetImageID") and my container is using SqlDataSource1 which has a text Sql query.

Thats it really...if you just want to throw an Image control on the form then it loojks like this:

<asp:Image ID="Image1" ImageUrl="" runat="server" />

Code behind...

 this.Image1.ImageUrl = FormatURL(ParameterImageID);

..and the GetImage.aspx page will get the ID and pass it to the method we have seen above.

Now make sure you placed the Optimizer control on your form so it is registered on the page..

<%@ Register Src="DHQImage.ascx" TagName="DHQImage" TagPrefix="uc1" %>

Lets see....

The thumbnail piece....not sure why you would go through all that???? I already have the image and I optimized it once. I could change the properties and pass the image through it again to make it much smaller and save both. One as the regular optimized and the other as a really optimized (smaller version). Unless I'm missing something thats what I would do....

Hope this helps

# June 22, 2007 12:59 PM

Eric Wise said:

There is working code in the easy assets .net source code which is available at www.easywebapps.com

# June 24, 2007 6:56 PM

Chuck Mahenski said:

The Image Optimizer dll fails to work on hosted accounts. You may get an error  "System.Security.SecurityException: That assembly does not allow partially trusted callers." This is because they didn't add "Allow Partially Trusted Callers Attribute (APTC) attribute" to the assembly. I assume this only happens with the free download. Maybe this is not an issue if you want to pay for this "Free" control.

-Chuck

# July 9, 2007 7:33 PM

Chuck Mahenski said:

Eric, my solution works great locally. I noticed when I deploy my site and access the page where I'm using the Image optimizer control I get an err: System.Security.SecurityException: That assembly does not allow partially trusted callers. Is the paid version of this control signed??

# July 9, 2007 7:42 PM

Eric Wise said:

Honestly I have no idea whether it is signed.  When I wrote this article and used this control back in 2005 it was free.  I haven't kept up with future releases.

# July 9, 2007 8:45 PM

RT said:

Eric,

How did you do your onclick function to allow for the thumbnail image to display the original image?

Thanks

# August 1, 2007 3:42 PM

chary said:

hi am new to this image uploading to sql server. actually i'm in dilemma whether to store my images in sql server or in a file system. My data may contain 200000 records with each images size around 250KB. and it'll grow around 2% per month. I would appreciate your suggestion regd the same.

# August 24, 2007 10:46 AM

Eric Wise said:

Chary-

It depends on the size and power of your database. 200,000 records really isn't all that many in the grand scheme of things.

Will you have a process in place to backup and purge old data?

# August 29, 2007 11:02 AM

Chary said:

Thnx Eric for the reply.

Our client insisted to store in filesystem

# September 3, 2007 11:09 AM

Mrbronz said:

Very impressive code snippet, this has kept me going for hours and I must say I am really enjoying it.

Is there a chance you can put some comments in the VB code so that I can dissect it and understand it?

I�m trying to understand how you are uploading the thumbnail when you don�t have a connection string!

I know your code must work from your other classes but I can�t seem to understand where or how your connection string is used.

Kind Regards and thank God for people like you�

# September 19, 2007 7:21 PM

ipod downloads said:

Can you help me out please? Im moving onto ASP.net c# from Perl and PHP.

Starting with the basics I sett up a simple site with content management system.

I need to upload images and attach them to pages. (simple enough for me in php and perl!)

So after building the content management side (simple add page and modify page scripts) I decided to add a couple of pages which are for adding images and browsing images in the database.

I admit I find it hard to read c# at the moment but I picked out a couple of lines from your code  and added them to my code...eventually I had this:-

byte[] b = (byte[])dt.Rows[0]["data"];

System.Web.UI.WebControls.Image i = new System.Web.UI.WebControls.Image();

Response.OutputStream.Write(b, 0, b.Length);

and this outputs an image!!! Whoop! Wahey!

Now can I ask you how I store that image in a tempory file so I can call it with <asp:img> image tag and set its size and height?

Your help is much appreciated :))

G

# December 3, 2007 10:35 AM

BOTROS said:

Thank you very much

this article is very useful

# December 3, 2007 1:33 PM

rajko said:

Hi, beginner here, but..

1 kilobyte = 1024 bytes, not 1000 bytes

# December 27, 2007 5:44 AM

Khalid said:

Hai developer

I have few questions firstly we have to bought the compressor component or its freeware software. Without compressor compnent we cannot compress the photo files is it mandatory to have the component.

If you can give the code without compressor component it will be great help.

# February 1, 2008 12:08 AM

Robert said:

Thanks for the post,

I tried the http://www.imageoptimizer.net component in my app, it works really good. I can't believe how I was doing without it so far... Thanks a million.

Rob

# February 6, 2008 9:14 AM

ranjeet said:

hi eric the code is excellent when i tested some , but i got stucked up at one thing that is whats "DomainManager" what is that you are doing in that.

Can you please help me out. and one more thing after downloading and using the image optimizer dll i found that it creates a website address over the thumbnail..i need to remove that can you please let me known..

thanks & Regards

Ranjeet Kumar

# March 4, 2008 8:03 PM

venkat said:

hi i am venkat this is my id venkat5054@rediffmail.com can  u pls send ur full code.. to my id and alos tell how shall i add the DLL files , when i clickt the link it show some page , tell wat the procedure to get the tool in tat page..

Thanks...

# May 17, 2008 12:22 AM

Reality Me » Do you store images in a database? said:

Pingback from  Reality Me &raquo; Do you store images in a database?

# July 11, 2008 11:15 AM
Check out Devlicio.us!

Our Sponsors

Proudly Partnered With