You may use this method to resize image and set the maximum side size in pixels when uploading. You will need a reference to System.Drawing and System.Drawing.Imaging namespaces public void ResizeFromStream(string ImageSavePath, int MaxSideSize, Stream Buffer)
{ int intNewWidth; int intNewHeight; Image imgInput = Image.FromStream(Buffer); //Determine image format ImageFormat fmtImageFormat = imgInput.RawFormat; //get image original width and height int intOldWidth = imgInput.Width; int intOldHeight = imgInput.Height;
//determine if landscape or portrait int intMaxSide; if (intOldWidth >= intOldHeight) { intMaxSide = intOldWidth; } else { intMaxSide = intOldHeight; } if (intMaxSide > MaxSideSize) { //set new width and height double dblCoef = MaxSideSize / (double)intMaxSide;
i ntNewWidth = Convert.ToInt32(dblCoef * intOldWidth); intNewHeight = Convert.ToInt32(dblCoef * intOldHeight); } else { intNewWidth = intOldWidth; intNewHeight = intOldHeight; } //create new bitmap Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight);
//save bitmap to disk bmpResized.Save(ImageSavePath, fmtImageFormat); //release used resources imgInput.Dispose(); bmpResized.Dispose(); Buffer.Close(); }
What's the difference between the GetThumbnailImage() method and just creating a new image from an old image passing it width/height? It looks like the GetThumbnailImage loses more quality even if you keep it the same size than creating a whole new image of
the same size. Anyone know what these two techniques are doing under the hood? Why don't they retain the same quality and resolution if you're creating an image of the same size? Here are my stats doing both: The original .jpg is 80k at 400x500 (hor. res.=72,
vert. res.=72) When I use GetThumbnailImage() and pass it 400x500, the resulting file size is then 28k (hor. res.=282, vert. res.= 281) and real blurry. When I create a new bitmap and save as Jpeg at 400x500, the resulting file size is then 38k (hor. res.=96,
vert. res.= 96) and the quality is almost as good as the original. What gives?
Excellent question! I'd like to see some responses from image processing experts for this. As far as I know, sometimes thumbnail data is already embeded in images and I think that this data is not always correct in terms of quality and resolution, especially
if image has been compressed multiple times. GetThumbnailImage() extracts this thumbnail data and resize it to the specified size. Take a look at Remarks section in reference: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdrawingimageclassgetthumbnailimagetopic.asp
It is unpredictible what kind of image will be posted by user via HTTP, this is why I used the "new bitmap" technique in sample method.
Converted it to VB. Looks simple enough. Gonna modify it. What I want to do is simply get the size coordinates. I am going to use this in an ASP page but only to show the image. Therefore, I don't have to do anything to the image, just set the width and height.
Has anybody tried this?
Anyone have issues with the code above? I put that code in a method and passed "File1.PostedFile.InputStream" to the method but when the code gets to this line "System.Drawing.Image imgInput = System.Drawing.Image.FromStream(Buffer);" it says this error about
that line "System.ArgumentException: Invalid parameter used." any ideas? If I move this code out of a method and have it as all inline code it works fine. I think I am not passing the inputstream into the method correctly? Please help....
Hi, Johndev This sample is ready-to-use method, this is why you don't have to put it in a method - just put it in a class. //Your *.cs file: ////////////////////////////// using System.Drawing; using System.Drawing.Imaging; namespace Sample.Content.Items {
public class C_Image { public void ResizeFromStream(string ImageSavePath, int MaxSideSize, Stream Buffer) { //... } //... } } //////////////////////////////// //Your *.aspx or file: //////////////////////////////// using System; using System.Web; using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls; using Sample.Content.Items; namespace Sample { public class ImageUpload : System.Web.UI.Page { // submit button control protected Button btnSend; // file input control protected HtmlInputFile FileInput; private void btnSend_Click(object
sender, EventArgs e) { UploadImage(); } override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { btnSend.Click += new EventHandler(btnSend_Click); } private void UploadImage() { if(FileInput.PostedFile
!= null ) { // Get a reference to PostedFile object HttpPostedFile myFile = FileInput.PostedFile; // Get size of uploaded file int nFileLen = myFile.ContentLength; // make sure the size of the file is > 0 if( nFileLen > 0 ) { //initialize C_Image class C_Image
objImage = new C_Image(); //resize objImage.ResizeFromStream("C:\\", 200, myFile.InputStream); } } } } } //////////////////////////////// I'd suggest to check an extension of uploading file also to see if its actually an image. You can do this with regular
expressions: public bool IsGraphic(string Path) { Regex r = new Regex(@"\.gif$|\.jpg$|\.jpeg$|\.png$", RegexOptions.IgnoreCase); if (r.IsMatch(Path)) { return true; } else { return false; } } Regards, Ilias Toprover
Thanks this was realy helpful. By the way what is the ImageFormat class used for. I thought that it would give me the image format of the uploaded object. I don't know how to get that other than porsing the filename and looking for the file ext. Any suggestions....
Can anyone provide method/code to crope an image while uploading?
asp.NET 2.0c#client side image compression
If this post is helpful, please mark as an answer. Visit My Blog : http://prajeeshkk.blogspot.com/ Regards,
Prajeesh.
Software Engineer
Speridian Technologies
What's the difference between the GetThumbnailImage() method and just creating a new image from an old image passing it width/height?
It looks like the GetThumbnailImage loses more quality even if you keep it the same size than creating a whole new image of the same size. Anyone know what these two techniques are doing under the hood? Why don't they retain the same quality and resolution
if you're creating an image of the same size?
Here are my stats doing both:
The original .jpg is 80k at 400x500 (hor. res.=72, vert. res.=72)
When I use GetThumbnailImage() and pass it 400x500, the resulting file size is then 28k (hor. res.=282, vert. res.= 281) and real blurry.
When I create a new bitmap and save as Jpeg at 400x500, the resulting file size is then 38k (hor. res.=96, vert. res.= 96) and the quality is almost as good as the original.
What gives?
Well, when I read up on this, GetThumbnailImage() method actually has a limitation in terms of size to resize to. I think this is around the 120px X 120px size. So if you pass it 400x500, it means the resizer is actually drawing the image smaller and then
stretching it out again which is why you are getting the blurry res. Resizing the Bitmap by using the save method doesnt do this which is why you get the same res.
intNewWidth = intOldWidth
intNewHeight = intOldHeight
End If
'create new bitmap
Dim bmpResized As Drawing.Bitmap = New Drawing.Bitmap(imgInput, intNewWidth, intNewHeight)
'save bitmap to disk
bmpResized.Save(ImageSavePath, fmtImageFormat)
'release used resources
imgInput.Dispose()
bmpResized.Dispose()
Buffer.Close()
End Sub
I downloaded the sample, and can't get it to work. When I click to upload the picture, the page just posts back to itself and I get a blank page. Have you been able to get this to work? I am using VisualStudio 2008, I tried with both the 2.0 and the
3.5 framework and it didn't make a difference.
I got the error when i didnt give the folder read and write permission to the ASP.NET user or the IIS user depending on your settings. Just give the user full control on the directory it is working in.
Make sure to give the folder the control perfoming its work on access to the ASP.NET user or if you are using the IIS_USR, make sure you give it full access.
Imports System.Configuration
Imports System.IO
Imports System.Drawing
Imports System.Collections.Generic
Imports System.Web
Imports System.Web.UI
Imports System.Collections
Imports System.Web.Security
Imports System.Web.UI.HtmlControls
Imports System.Drawing.Color
Partial Class [yourClass]
Inherits Web.UI.Page
Sub ImageResize(ByVal strDest As String)
Const intMaxWidth As Integer = 300 'max width
Const intMaxHgt As Integer = 300 'max height
Dim intNewWidth, intNewHgt As Integer ' new width/height
Dim sglSize As Single 'temp variable used when calculating new size
Dim imgOriginal As Image 'holds the original image
Dim ful As FileUpload = Util.FindChild(Me, "Upload")
If ful IsNot Nothing Then
imgOriginal = Image.FromStream(ful.FileContent)
If (imgOriginal.Width / intMaxWidth) > (imgOriginal.Height / intMaxHgt) Then
sglSize = imgOriginal.Width
intNewWidth = intMaxWidth
intNewHgt = imgOriginal.Height * (intMaxWidth / sglSize)
If intNewHgt > intMaxHgt Then
intNewWidth = intNewWidth * (intMaxHgt / intNewHgt)
intNewHgt = intMaxHgt
End If
Else
sglSize = imgOriginal.Height
intNewHgt = intMaxHgt
intNewWidth = imgOriginal.Width * (intMaxHgt / sglSize)
If intNewWidth > intMaxWidth Then
intNewHgt = intNewHgt * (intMaxWidth / intNewWidth)
intNewWidth = intMaxWidth
End If
End If
'Create a graphics object
Dim imgOutput As New Bitmap(intNewWidth, intNewHgt)
imgOutput = imgOriginal.GetThumbnailImage(intNewWidth, intNewHgt, Nothing, IntPtr.Zero)
Dim gr_dest As Graphics = Graphics.FromImage(imgOutput)
'Re-draw the image to the specified height and width
gr_dest.DrawImage(imgOriginal, 0, 0, imgOutput.Width, imgOutput.Height)
imgOutput.Save(Server.MapPath(strDest), imgOriginal.RawFormat)
End If
End Sub
Thanks for Code. This code is working fine in local host. But when i put it on the IIS (Shared hosting) then it gives error near bmpResized.Save(ImageSavePath, fmtImageFormat). I tried all the ways Server.MapPath...) , System.Web.HttpContext.Current.Request.PhysicalApplicationPath,
I tried all the possible ways. But same error.
Can u please mail me the Vb.Net code and dll generated in Vb.Net Version at anil12398@gmail.com or anil12398@yahoo.com. I would be very thankful to you.
if you want to resize image than using asp,net-2.0(vb)
more about how to resize image , i will you suggest you to visit the below link
http://www.raiseitsolutions.com/forum/viewtopic.php?f=4&t=3
please visit the link, here you can know about resizing image.
thank you very much.
The method takes two objects - the image to crop (System.Drawing.Image) and the rectangle to crop out (System.Drawing.Rectangle). The next thing done is to create a Bitmap (System.Drawing.Bitmap) of the image. The only thing left is to crop the image. This
is done by cloning the original image but only taking a rectangle of the original.
None
0 Points
3 Posts
Resize image when uploading (C#)
Aug 11, 2002 06:29 AM|IliaT|LINK
None
0 Points
20 Posts
Re: Resize image when uploading (C#)
Aug 20, 2002 10:45 PM|Tekmaven|LINK
Member
24 Points
210 Posts
ASPInsiders
MVP
Re: Resize image when uploading (C#)
Aug 21, 2002 12:15 AM|ASPSmith|LINK
http://SteveSmithBlog.com
http://Twitter.com/Ardalis
The Code Project (www.codeproject.com)
Founder, NimblePros (nimblepros.com)
None
0 Points
63 Posts
Re: Resize image when uploading (C#)
Aug 23, 2002 11:51 PM|gbrown|LINK
None
0 Points
3 Posts
Re: Resize image when uploading (C#)
Aug 24, 2002 02:36 AM|IliaT|LINK
None
0 Points
5 Posts
Re: Resize image when uploading (C#)
Sep 06, 2002 08:40 AM|qwert231|LINK
None
0 Points
1 Post
Re: Resize image when uploading (C#)
Sep 06, 2002 03:51 PM|johndev|LINK
None
0 Points
3 Posts
Re: Resize image when uploading (C#)
Sep 06, 2002 10:38 PM|IliaT|LINK
None
0 Points
34 Posts
Re: Resize image when uploading (C#)
Nov 17, 2003 08:00 PM|SosaWISE|LINK
Participant
966 Points
259 Posts
Re: Resize image when uploading (C#)
Dec 15, 2007 10:24 AM|prajeeshkkindia|LINK
Can anyone provide method/code to crope an image while uploading?
asp.NET 2.0 c# client side image compression
Visit My Blog : http://prajeeshkk.blogspot.com/
Regards,
Prajeesh.
Software Engineer
Speridian Technologies
None
0 Points
1 Post
Re: Resize image when uploading (C#)
Jun 03, 2008 08:25 PM|yippanion|LINK
Well, when I read up on this, GetThumbnailImage() method actually has a limitation in terms of size to resize to. I think this is around the 120px X 120px size. So if you pass it 400x500, it means the resizer is actually drawing the image smaller and then stretching it out again which is why you are getting the blurry res. Resizing the Bitmap by using the save method doesnt do this which is why you get the same res.
None
0 Points
7 Posts
Re: Resize image when uploading (C#)
Jul 22, 2008 11:49 PM|Carteja|LINK
This is how the vb code for the resize image
Imports System.IO.Path
Imports System.Drawing.Imaging
Public Sub ResizeFromStream(ByVal ImageSavePath As String, ByVal MaxSideSize As Integer, ByVal Buffer As System.IO.Stream)
Dim intNewWidth As Integer
Dim intNewHeight As Integer
Dim imgInput As System.Drawing.Image = System.Drawing.Image.FromStream(Buffer)
'Determine image format
Dim fmtImageFormat As ImageFormat = imgInput.RawFormat
'get image original width and height
Dim intOldWidth As Integer = imgInput.Width
Dim intOldHeight As Integer = imgInput.Height
'determine if landscape or portrait
Dim intMaxSide As Integer
If (intOldWidth >= intOldHeight) Then
intMaxSide = intOldWidth
Else
intMaxSide = intOldHeight
End If
If (intMaxSide > MaxSideSize) Then
'set new width and height
Dim dblCoef As Double = MaxSideSize / CDbl(intMaxSide)
intNewWidth = Convert.ToInt32(dblCoef * intOldWidth)
intNewHeight = Convert.ToInt32(dblCoef * intOldHeight)
Else
intNewWidth = intOldWidth
intNewHeight = intOldHeight
End If
'create new bitmap
Dim bmpResized As Drawing.Bitmap = New Drawing.Bitmap(imgInput, intNewWidth, intNewHeight)
'save bitmap to disk
bmpResized.Save(ImageSavePath, fmtImageFormat)
'release used resources
imgInput.Dispose()
bmpResized.Dispose()
Buffer.Close()
End Sub
None
0 Points
7 Posts
Re: Resize image when uploading (C#)
Sep 04, 2008 04:13 PM|Carteja|LINK
Hi prajeeshkkindia,
Here is a great opens source tool that allows a user to actually resize his or her image and crop it to any size.
Its really good!
http://www.theguildnetwork.com/tgn/articles/imageControl_page1.aspx
If you need a dll file for the vb version let me know, i re-did mine in VB.NET
Member
1 Points
5 Posts
Re: Resize image when uploading (C#)
Sep 23, 2008 02:48 PM|toekneeh|LINK
Hi Carteja,
I downloaded the sample, and can't get it to work. When I click to upload the picture, the page just posts back to itself and I get a blank page. Have you been able to get this to work? I am using VisualStudio 2008, I tried with both the 2.0 and the 3.5 framework and it didn't make a difference.
-Tony
None
0 Points
7 Posts
Re: Resize image when uploading (C#)
Sep 24, 2008 11:18 AM|Carteja|LINK
Yes I did, However I re-did it in Vb.Net due to the fact that when tried to use the C# version I was getting a problem with the control it self.
If you would like the Vb.net version or the DLL file you can let me know and I will send it to your email.
Member
39 Points
212 Posts
Re: Resize image when uploading (C#)
Oct 27, 2008 12:15 AM|cutekids525|LINK
Hi... I have used your code..but i am getting the following error...
System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+
Please suggest me...
Thanks,
Praveen
Cute
None
0 Points
7 Posts
Re: Resize image when uploading (C#)
Oct 27, 2008 10:57 AM|Carteja|LINK
I got the error when i didnt give the folder read and write permission to the ASP.NET user or the IIS user depending on your settings. Just give the user full control on the directory it is working in.
None
0 Points
7 Posts
Re: Resize image when uploading (C#)
Aug 18, 2009 03:37 PM|Carteja|LINK
Make sure to give the folder the control perfoming its work on access to the ASP.NET user or if you are using the IIS_USR, make sure you give it full access.
Member
13 Points
19 Posts
Re: Resize image when uploading (C#)
Dec 21, 2009 12:38 PM|romah|LINK
Hi all,
I am trying to run this code from asp.net button click event. I got an exception error on this line.
bmpResized.Save(ImageSavePath, fmtImageFormat);
It says "A generic error occurred in GDI+"
I have searched this error in forum and most of the post says "this is because of permission".
I am using administrator and I didn't see any restriction to copy and create any files in c:\temp\
Other post says "Need to put GC.Collect()". I also added that method but again the same error.
Why is that problem occurred?
Member
571 Points
139 Posts
Re: Resize image when uploading (C#)
Dec 22, 2009 08:56 AM|Pankaj Rai|LINK
Please refer this link .....
http://weblogs.asp.net/markmcdonnell/archive/2008/03/09/resize-image-before-uploading-to-server.aspx
S/W Developer
NetCarrots Loyalty Services
New Delhi
Please remember to click “Mark as Answer” on the post that helps you
None
0 Points
15 Posts
Re: Resize image when uploading (C#)
Feb 24, 2010 01:24 AM|SalMan_pc|LINK
How Can I call This Method For Upload a image
i have a folder (Products) ,Iwant to upload images to this folder in same size
pls replay me..
Member
308 Points
1544 Posts
Re: Resize image when uploading (C#)
Mar 02, 2010 04:20 PM|muybn|LINK
This worked for me (in VB):
None
0 Points
12 Posts
Re: Resize image when uploading (C#)
Jul 10, 2010 01:40 AM|anishbhagwat80|LINK
Thanks for Code. This code is working fine in local host. But when i put it on the IIS (Shared hosting) then it gives error near bmpResized.Save(ImageSavePath, fmtImageFormat). I tried all the ways Server.MapPath...) , System.Web.HttpContext.Current.Request.PhysicalApplicationPath, I tried all the possible ways. But same error.
Please help me.
None
0 Points
2 Posts
Re: Resize image when uploading (C#)
Nov 23, 2010 07:30 AM|anil12398|LINK
Hi Carteja,
Can u please mail me the Vb.Net code and dll generated in Vb.Net Version at anil12398@gmail.com or anil12398@yahoo.com. I would be very thankful to you.
Thanks
Anil
None
0 Points
2 Posts
Re: Resize image when uploading (C#)
Nov 23, 2010 11:58 PM|anil12398|LINK
Hi,
Please provide me Vb.net version and dll file at anil12398 of gmail dot com. I would be very thankful to you.
Thanks
anil
Member
103 Points
796 Posts
Re: Resize image when uploading (C#)
Dec 23, 2010 05:46 AM|kengkit|LINK
may i know what's Util.FindChild(Me, "Upload")
hundred thanks
None
0 Points
8 Posts
Re: Resize image when uploading (C#)
Dec 24, 2010 04:07 AM|waqar-ahmad|LINK
You check this link. I think it might be helpful in your case. This code work for me perfect.
http://waqarahmadbhatti.blogspot.com/2010/12/image-scaling-without-cutting-image.html
Waqar Sher Bhatti
http://waqarsherbhatti.posterous.com/
None
0 Points
2 Posts
Re: Resize image when uploading (C#)
Jan 10, 2011 04:10 AM|inzamam|LINK
if you want to resize image than using asp,net-2.0(vb)
more about how to resize image , i will you suggest you to visit the below link
http://www.raiseitsolutions.com/forum/viewtopic.php?f=4&t=3
please visit the link, here you can know about resizing image.
thank you very much.
None
0 Points
2 Posts
Re: Resize image when uploading (C#)
May 02, 2011 04:04 PM|graphic-design-software|LINK
Is the above software code fast for resizing large photos? I need the fastest possible function for my online graphic design software.
Member
557 Points
196 Posts
Re: Resize image when uploading (C#)
May 03, 2011 10:13 AM|Abhimanyu Kumar Vatsa|LINK
the best article to learn this
http://www.mikesdotnetting.com/Article/95/Upload-and-Crop-Images-with-jQuery-JCrop-and-ASP.NET
Member
70 Points
34 Posts
Re: Resize image when uploading (C#)
May 31, 2011 11:00 AM|nathanael.jones@gmail.com|LINK
This is a much simpler explanation, and includes a sample project:
Combining jCrop and server-side image resizing in 11 lines
The sample project
The basic demo
The advanced demo
Member
27 Points
55 Posts
Re: Resize image when uploading (C#)
Oct 13, 2011 01:18 AM|Shailen|LINK
Hi Here is the code for cropping the image in C#
Cropping
The method takes two objects - the image to crop (System.Drawing.Image) and the rectangle to crop out (System.Drawing.Rectangle). The next thing done is to create a Bitmap (System.Drawing.Bitmap) of the image. The only thing left is to crop the image. This is done by cloning the original image but only taking a rectangle of the original.
<div class="geshifilter"> <div class="csharp geshifilter-csharp">private static Image cropImage(Image img, Rectangle cropArea){
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea,
bmpImage.PixelFormat);
return (Image)(bmpCrop);
}</div> <div class="csharp geshifilter-csharp"></div> <div class="csharp geshifilter-csharp">Hope this helps you.</div> </div>
client side image compression
Shailen
Visit My Blog