locked
Resize image when uploading (C#) RRS feed

  • Question

  • User846986586 posted
    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(); }
    Sunday, August 11, 2002 6:29 AM

All replies

  • User-387796430 posted
    Is there anyone who can translate this code to VB? I am in the dark with C#.. TIA!
    Tuesday, August 20, 2002 10:45 PM
  • User-815529067 posted
    Use Alex Lowe's C# to VB Translation Tool at ASPAlliance.com. Steve
    Wednesday, August 21, 2002 12:15 AM
  • User-1996987520 posted
    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?
    Friday, August 23, 2002 11:51 PM
  • User846986586 posted
    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.
    Saturday, August 24, 2002 2:36 AM
  • User383070814 posted
    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 <asp:Image /> width and height. Has anybody tried this?
    Friday, September 6, 2002 8:40 AM
  • User-2122888528 posted
    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....
    Friday, September 6, 2002 3:51 PM
  • User846986586 posted
    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
    Friday, September 6, 2002 10:38 PM
  • User-1348097813 posted
    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....
    Monday, November 17, 2003 8:00 PM
  • User1774691446 posted

    Can anyone provide method/code to crope an image while uploading?

    Saturday, December 15, 2007 10:24 AM
  • User1792951536 posted

    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.

    Tuesday, June 3, 2008 8:25 PM
  • User319397123 posted

    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

    Tuesday, July 22, 2008 11:49 PM
  • User319397123 posted

     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

    Thursday, September 4, 2008 4:13 PM
  • User-1920518973 posted

    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

    Tuesday, September 23, 2008 2:48 PM
  • User319397123 posted

    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.

    Wednesday, September 24, 2008 11:18 AM
  • User411781540 posted

    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

    Monday, October 27, 2008 12:15 AM
  • User319397123 posted

     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.

    Monday, October 27, 2008 10:57 AM
  • User319397123 posted

    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.

    Tuesday, August 18, 2009 3:37 PM
  • User-1553693074 posted

    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?

    Monday, December 21, 2009 12:38 PM
  • Tuesday, December 22, 2009 8:56 AM
  • User-739890161 posted

    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..

    Wednesday, February 24, 2010 1:24 AM
  • User1280950372 posted

    This worked for me (in VB):

    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
    Tuesday, March 2, 2010 4:20 PM
  • User2103493169 posted

    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.

    Saturday, July 10, 2010 1:40 AM
  • User-594810903 posted

    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


    Tuesday, November 23, 2010 7:30 AM
  • User-594810903 posted

    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

    Tuesday, November 23, 2010 11:58 PM
  • User944339287 posted

    may i know what's Util.FindChild(Me, "Upload")

    hundred thanks

    Thursday, December 23, 2010 5:46 AM
  • User1833584855 posted

    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

    Friday, December 24, 2010 4:07 AM
  • User-443690043 posted

    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.

    Monday, January 10, 2011 4:10 AM
  • User1338478216 posted

    Is the above software code fast for resizing large photos? I need the fastest possible function for my online graphic design software.

    Monday, May 2, 2011 4:04 PM
  • Tuesday, May 3, 2011 10:13 AM
  • User1792244448 posted

    This is a much simpler explanation, and includes a sample project:

    Combining jCrop and server-side image resizing in 11 lines 

    The sample project
    <meta charset="utf-8" />

    The basic demo

    The advanced demo

    Tuesday, May 31, 2011 11:00 AM
  • User839650768 posted

    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.

    private static Image cropImage(Image img, Rectangle cropArea)
    {
       Bitmap bmpImage = new Bitmap(img);
       Bitmap bmpCrop = bmpImage.Clone(cropArea,
       bmpImage.PixelFormat);
       return (Image)(bmpCrop);
    }
    Hope this helps you.
    Thursday, October 13, 2011 1:18 AM