image resize function producing 2 images of same size instead of thumb and large sizes

my code is meant 2 insert 2x images into the database. one medium size, and one thumbnail. unfortunately it seems to be inserting 2x images of the same size into the database. the images are retrieved using and event handler which works fine. i have isolated it to be my resize function:

  
1    using System;
2    using System.Data;
3    using System.Data.Sql;
4    using System.Data.SqlClient;
5    using System.Configuration;
6    using System.Collections;
7    using System.Web;
8    using System.Web.Security;
9    using System.Web.UI;
10   using System.Web.UI.WebControls;
11   using System.Web.UI.WebControls.WebParts;
12   using System.Web.UI.HtmlControls;
13   using System.Drawing;
14   using System.Drawing.Imaging;
15   using System.IO;
16   
17   
18   public partial class binary : System.Web.UI.Page
19   {
20       int maxImgWidth = 300; //Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["max_picture_height"]);
21       int maxImgHeight = 300;
22       int maxThumbWidth = 120;
23       int maxThumbHeight = 120;
24   
25       protected void Page_Load(object sender, EventArgs e)
26       {
27           
28       }
29   
30       //on edit use content length and filename to make comparison to see if file should be updated
31       //or use viewstate to trap whether image "browse" button has been clicked
32       //limit lenght of the file name to 50 chars
33       protected void btnAdd_Click(object sender, EventArgs e)
34       {
35           if (upFile.HasFile)
36           {
37               if (CheckFileType(upFile.FileName))
38               {   
39                   srcFiles.Insert();                
40               }
41               else
42               {
43                   lblMessage.Text = "Invalid file type. Must be .jpg or .gif";
44               }
45           }
46       }
47   
48       #region Inserting Record
49       protected void srcFiles_Inserting(object sender, SqlDataSourceCommandEventArgs e)
50       {
51           HttpPostedFile file = (HttpPostedFile)(upFile.PostedFile);
52                   
53           //Medium Size Image
54           SqlParameter pImage = new SqlParameter();
55           pImage.ParameterName = "@FileBytes";
56           pImage.SqlDbType = SqlDbType.Image;        
57           pImage.Value = ResizeImage(file,maxImgWidth, maxImgHeight);
58           e.Command.Parameters.Add(pImage);
59   
60           //Thumbnail
61           SqlParameter pThumb = new SqlParameter();
62           pThumb.ParameterName = "@ThumbBytes";
63           pThumb.SqlDbType = SqlDbType.Image;
64           pThumb.Value = ResizeImage(file, maxThumbWidth, maxThumbHeight);
65           e.Command.Parameters.Add(pThumb);
66   
67           SqlParameter pLength = new SqlParameter();
68           pLength.ParameterName = "@FileLength";
69           pLength.SqlDbType = SqlDbType.Int;
70           pLength.Value = file.ContentLength;
71           e.Command.Parameters.Add(pLength);
72           
73       }
74       #endregion
75   
76       #region Resize Image
77       private byte[] ResizeImage(HttpPostedFile file, int maxWidth, int maxHeight)
78       {
79           int fileSize = file.ContentLength;
80           byte[] myData = new byte[fileSize];
81           file.InputStream.Read(myData, 0, fileSize);
82   
83           System.Drawing.Image img = System.Drawing.Image.FromStream(file.InputStream);
84   
85           int imgWidth = img.Width;
86           int imgHeight = img.Height;
87           double percent2Shrink = -1;
88   
89           if (imgWidth >= imgHeight)
90           {
91               if (imgWidth > maxWidth)            
92                   percent2Shrink = (double)maxWidth / (double)imgWidth;            
93           }
94           else
95           {
96               if (imgHeight > maxHeight)            
97                   percent2Shrink = (double)maxHeight / (double)imgHeight;            
98           }
99   
100          int newWidth = imgWidth;
101          int newHeight = imgHeight;
102  
103          // Is resize required?
104          if (percent2Shrink != -1)
105          {
106              newWidth = (int)(imgWidth * percent2Shrink);
107              newHeight = (int)(imgHeight * percent2Shrink);
108          }
109                  
110          System.Drawing.Bitmap bmp = new Bitmap(newWidth, newHeight);
111          
112          using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
113          {            
114              g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
115              g.FillRectangle(Brushes.White, 0, 0, newWidth, newHeight);            
116              g.DrawImage(img, 0, 0, newWidth, newHeight);
117          }
118          
119          MemoryStream stream = new MemoryStream();        
120          bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
121  
122          img.Dispose();
123          bmp.Dispose();        
124  
125          byte[] imgBinaryData = stream.ToArray();
126  
127          return imgBinaryData;
128      }
129      #endregion
130  
131      #region Check File Extension
132      private bool CheckFileType(string fileName)
133      {
134          if (Path.GetExtension(fileName).ToLower() == ".jpg")
135          {
136              return true;
137          }
138          else if (Path.GetExtension(fileName).ToLower() == ".gif")
139              return true;
140          else
141              return false;
142      }
143      #endregion
144  }
  any ideas?
0
LeMerovingian
2/15/2007 5:50:42 AM
asp.net.drawinggdi 1803 articles. 0 followers. Follow

0 Replies
869 Views

Similar Articles

[PageSpeed] 41

Reply:

Similar Artilces:

DPI & Image size... How can I display an image with a high DPI as large on screen and have it print at its smaller Image size?
I was wondering if anyone could help with this.If I have an image I'm rendering through Bitmap.Save(Response.Outputstream,  ImageFormat.Jpeg)  it's 300 DPI with a WidthxHeight of ~3inch by ~2inch (~1000 X ~700 pixels), How can I display it on screen at its resolution but print it at its widthxheight. In photoshop the image is large on screen and correclty sized on the print out...when i render it in my web app its small on screen and correclty sized on the print out. Thanks.  I have found my problem :¬DPrinting via IE ignores the set resolution and just prints the ...

superreview requested: [Bug 207219] Image Resize: Clicking to restore large size should center at clicked position (image should scroll so that cursor would remain exactly above the same pixel) : [At #2
Chris Thomas (CTho) <cst@andrew.cmu.edu> has asked Peter Van der Beken <peterv@propagandism.org> for superreview: Bug 207219: Image Resize: Clicking to restore large size should center at clicked position (image should scroll so that cursor would remain exactly above the same pixel) https://bugzilla.mozilla.org/show_bug.cgi?id=207219 Attachment 177610: zoom to the right place https://bugzilla.mozilla.org/attachment.cgi?id=177610&action=edit ...

getting remote image sizes with image::size lwp
I am trying to get the width and height attributes of jpg's and gif's on a remote server. I have found Image::Size and LWP but am unable to put them together so that I can open an http path (e.g. http://wwwfoobar.com/dirname/dirname/dirname/images/111203.gif) and print out the image size. Any help would be appreciated including where I might go to read more on this. TIA My first attempt that failed: #!/usr/bin/perl # The next few lines use the LWP (Library www perl) module # to read the files via http that each url points to. $the_url =3D 'http://wwwfoobar.com...

getting remote image size with Image::Size & LWP
=19 Thank you for your patience and help bringing me up to speed on how to be a better user of this list. My previous post was my first. I am trying to write a script that will use Image::Size module in conjunction with the LWP module to retrieve the height and width attribute of a gif or jpg on a remote server. Below the first script uses the Image::Size module and successfully returns the height and width of an image on the same volume. The second script uses the LWP module and depending on which version of $the_url is used, successfully returns the contents of an html file or an ...

superreview requested: [Bug 207219] Image Resize: Clicking to restore large size should center at clicked position (image should scroll so that cursor would remain exactly above the same pixel) : [At #3
Chris Thomas (CTho) <cst@andrew.cmu.edu> has asked Robert O'Callahan (Novell) <roc@ocallahan.org> for superreview: Bug 207219: Image Resize: Clicking to restore large size should center at clicked position (image should scroll so that cursor would remain exactly above the same pixel) https://bugzilla.mozilla.org/show_bug.cgi?id=207219 Attachment 177610: zoom to the right place https://bugzilla.mozilla.org/attachment.cgi?id=177610&action=edit ...

superreview requested: [Bug 175787] Resize large images to fit in treeview instead of cropping : [Attachment 219780] v2 patch - works for images specified by src and css, text is painted properly #2
Liz Looney <looney.liz@gmail.com> has asked Brian Ryner <bryner@brianryner.com> for superreview: Bug 175787: Resize large images to fit in treeview instead of cropping https://bugzilla.mozilla.org/show_bug.cgi?id=175787 Attachment 219780: v2 patch - works for images specified by src and css, text is painted properly https://bugzilla.mozilla.org/attachment.cgi?id=219780&action=edit ...

Creating Thumbnail Images
Hi all, I have a script that uploads an image and creates a thumbnail for it. Ideally this thumbnail would be a smaller filesize but this is not what is happening. I have just uploaded a few images one of which was 378x521px and 11.3Kb. The thumbnail image created from this was 145x200 and 55.5Kb! Can anyone please tell me what I am doing wrong. I am using the GetThumbnailImage method as such:  System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(intThumbWidth, intThumbHeight, myCallBack, IntPtr.Zero);myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile)); Many thank...

Image size for Image Explorer
What's the maximum size imagethat can be loaded into Image explorer (imgexp.exe)? Thanks -- ========================================================================= Patrick Doherty | United Biscuits (UK) Ltd | ------------------------------------------------------------------------| People ask me why I play with computers at home when I use them at work.| They don't understand--I play with computers at work, too | ======================================...

Image size
I m getting Image URL from Other Server. I have to get the size of Image URL with out saving .Is It Possible? Please Help Me. please elaborate...Chinna_sv... alagarm:I m getting Image URL from Other Server. I have to get the size of Image URL with out saving .Is It Possible? Hi,I'm not really sure If I follow you but if you wan't to resize the image before saving it then this article below should help you:Resize image BEFORE saving to server Regards,Vinz"Code, Beer and Music" that's my way of being a programmer!How to get your Forum Question Answered | Blog |...

Problems with a thumbnail image to popup Full-size image (image paths from a database)
I am hoping to get more feedback from entering this in perhaps a more appropriate forum.   Please refer to post   http://forums.asp.net/thread/1540002.aspx   I think I’ve explained what I would like to do but can’t figure out how to successfully code it.   I found it interesting that if I removed the Onclick event, my Bind error goes away.   And changing the Bind to an Eval traded the Bind error for a parser error.   How can I pass the path of the Full size image from my DB to the javascript so that ASP and Java both are OK with the coding?  ...

Image size #2
------=_NextPart_000_0095_01C1BF65.2BA0B8C0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Well, I tryed to include this code, but I was unsuggessful. Here is the basic script: #!/usr/bin/perl use Image::Size; print "Content-type: text/html\n\r\n\r"; # Get the size of globe.gif ($globe_x, $globe_y) =3D imgsize("test.gif"); # Assume X=3D60 and Y=3D40 for remaining examples print "X: $globe_x, Y: $globe_y"; use Image::Size; # Get the size of globe.gif ($globe_x, $globe_y)...

image size #2
 I got a function that actually create the thumbnail image of a large image, I will use that thumbnail image to send it via mms. now the problem is i want to reduce the size of the image to minimum, like for example:If i pass large jpg image of size 181kb it create thumbnail image of 14K but if i pass a large bmp image of size 1.04MB it create thumbnail image of  222kb which is quite big size for an mms? Any idea how to control the thumbnail image size? Cheers  1 Public Shared Function CreateThumbnail(ByVal path As String, ByVal maxHeight As Integer, ByVal maxWidth...

Image Size #2
I have a PNG image that according to PrintShop is 6.17 Inches by 6.17 Inches(200 pixels per inch).  When I put an image control on the report and tell it to size to image it expands well beyond an 8.5 by 11 page.  What is going on?  The issue is that these images get generated on the fly by the customer and they must match exactly to the size generated.   Thanks Change your resolution to 72 DPI (dots per Inches) not pixels per inches.   200 is way too hich...

Get Image Size from New Image
Hi:I have an ASP.net application where I have a dropdown box and it fires an event to load a new image from my  SQL Server 2005 database.  I am able to show the image but would like to show the dimensions as a label but not able to do this. My code looks like this//This works fine - can load the image imgLargePic.ImageUrl = "~/Controls/Fetch_Pic.ashx?ProductPicID=" + iProductPicID + "&Size=Large";//Can't get this to work... - next line of code...lblPicSize.Text=imgLargePic.Width.Value.ToString() + "X" + imgLargePic.Height.ToString();  ...

Web resources about - image resize function producing 2 images of same size instead of thumb and large sizes - asp.net.drawinggdi

List of wine-producing regions - Wikipedia, the free encyclopedia
This list of wine-producing regions catalogues significant growing regions where vineyards are planted. Wine grapes mostly grow between the 30th ...

Involver adds visual tool for producing custom Facebook apps without code
Social marketing platform Involver today introduced a visual tool for building Facebook applications and other customizable experiences. The ...

Producing Revenue (@msdnbelux) on Twitter
Sign in Sign up To bring you Twitter, we and our partners use cookies on our and other websites. Cookies help personalize Twitter content, tailor ...

Scientists: Are we producing too many? - Flickr - Photo Sharing!
The short answer is: it depends on who you ask. The view of governments, universities and policy-makers is an emphatic "No." In fact, they argue ...

You Can Live Without Producing Trash - YouTube
One New York woman is making an effort to change the way we think about waste. Over the past two years, Lauren Singer has produced only enough ...

Pilot of the Day: Joel McHale is Producing a TV Show about Internet Commenters
“The Soup” host and “Community” star Joel McHale is about to take on the trolls! E! has greenlit his pilot for “Comments Section,” which will ...

Public service cuts producing errors, longer waiting times, says union
Mistakes are being made, intelligence and quarantine services are being cut and waiting times for Medicare and Centrelink services are growing ...

Hume drug lab capable of producing $15 million of MDMA, police say
The discovery of a clandestine drug lab in Hume last Tuesday has been described by police as the largest seizure of MDMA or ecstasy in ACT history ...

Potential diabetes therapy: scientists grow insulin-producing cells using cloning techniques
For the first time scientists have used cells from a woman with type 1 diabetes to create cloned human embryos from which they extracted embryonic ...

Global airlines to join Qantas in producing higher returns: IATA
Global airlines are poised to report a collective $US29.3 billion profit this year, with returns exceeding the cost of capital for the first ...

Resources last updated: 11/24/2015 4:19:12 PM