locked
Resize Images on upload RRS feed

  • Question

  • User60291871 posted

    Hi All,<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p>

    I'm developing a web site using VWD 2005 Express which allows users to upload images using the file upload control. Easy enough but I want to resize the uploaded images to ensure large file sizes are not saved and to reduce the picture sizes to no more than 300x200 pixels before I save them to disk. I've seen some code examples, mainly C#,  but nothing that clearly explains how to do this and nothing using VB code, which is my preference.  I'm looking for some code/pointers and ideas on how to achieve this. Can anyone help me out please?<o:p></o:p>

    Regards<o:p></o:p>

    Smcoxon

    Friday, March 9, 2007 2:32 PM

Answers

  • User-846453637 posted

    check this

        // Get the path of the original Image
         string displayedImg = Server.MapPath("~") + "/Testing.jpg";

        // Get the path of the Thumb folder
        string displayedImgThumb = Server.MapPath("~") + "/Thumb/";
        
        // Get the original image file name
        string imgFileName = System.IO.Path.GetFileName(displayedImg);
     
        // Load original image
        System.Drawing.Image myimg = System.Drawing.Image.FromFile(displayedImg);

        // Get the thumbnail 100 X 100 px
        myimg = myimg.GetThumbnailImage(100, 100, null, IntPtr.Zero);
        
       // Save the new thumbnail image
       myimg.Save(displayedImgThumb + imgFileName, myimg.RawFormat);

    Hope this helps

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 9, 2007 2:52 PM
  • User60291871 posted

    Thanks Ramzi,

    This has pointed me in the right direction. I'm now looking at the Graphics class too, so that I can do more with the original image. Once I have the code working as I want, I'll post it here for anyone else to use.

     Regards Sean.[8-|]

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, March 11, 2007 7:32 AM
  • User60291871 posted

    Here's my VB code as promised. I'm a newbee to VWD and ASP.NET and know how hard it can be to find useful code. My code might not be elegant but it works well for me! Hope it helps someone else.

     

    Imports System.IO

    Imports System.Drawing

     

    Partial Class _Default

    Inherits System.Web.UI.Page

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click

    Const bmpW = 300 'New image canvas width

    Const bmpH = 226 'New Image canvas height

    If (FileUpload1.HasFile) Then

    lblError.Text = ""

    'Check to make sure the file to upload has a picture file format extention

    If (CheckFileType(FileUpload1.FileName)) Then

    Dim newWidth As Integer = bmpW

    Dim newHeight As Integer = bmpH

    'Use the uploaded filename without the '.' extension

    Dim upName As String = Mid(FileUpload1.FileName, 1, (InStr(FileUpload1.FileName, ".") - 1))

    Dim filePath As String = "~/Upload/" & upName & ".png"

    'Create a new Bitmap using the uploaded picture as a Stream

    'Set the new bitmap resolution to 72 pixels per inch

    Dim upBmp As Bitmap = Bitmap.FromStream(FileUpload1.PostedFile.InputStream)

    Dim newBmp As Bitmap = New Bitmap(newWidth, newHeight, Imaging.PixelFormat.Format24bppRgb)

    newBmp.SetResolution(72, 72)

    'Get the uploaded image width and height

    Dim upWidth As Integer = upBmp.Width

    Dim upHeight As Integer = upBmp.Height

    Dim newX As Integer = 0

    Dim newY As Integer = 0

    Dim reDuce As Decimal

    'Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions

    'to ensure the image is always in the centre of the canvas vertically and horizontally

    If upWidth > upHeight Then 'Landscape picture

    reDuce = newWidth / upWidth 'calculate the width percentage reduction as decimal

    newHeight = Int(upHeight * reDuce) 'reduce the uploaded image height by the reduce amount

    newY = Int((bmpH - newHeight) / 2) 'Position the image centrally down the canvas

    newX = 0 'Picture will be full width

    ElseIf upWidth < upHeight Then 'Portrait picture

    reDuce = newHeight / upHeight 'calculate the height percentage reduction as decimal

    newWidth = Int(upWidth * reDuce) 'reduce the uploaded image height by the reduce amount

    newX = Int((bmpW - newWidth) / 2) 'Position the image centrally across the canvas

    newY = 0 'Picture will be full hieght

    ElseIf upWidth = upHeight Then 'square picture

    reDuce = newHeight / upHeight 'calculate the height percentage reduction as decimal

    newWidth = Int(upWidth * reDuce) 'reduce the uploaded image height by the reduce amount

    newX = Int((bmpW - newWidth) / 2) 'Position the image centrally across the canvas

    newY = Int((bmpH - newHeight) / 2) 'Position the image centrally down the canvas

    End If

    'Create a new image from the uploaded picture using the Graphics class

    'Clear the graphic and set the background colour to white

    'Use Antialias and High Quality Bicubic to maintain a good quality picture

    'Save the new bitmap image using 'Png' picture format and the calculated canvas positioning

    Dim newGraphic As Graphics = Graphics.FromImage(newBmp)

    Try

    newGraphic.Clear(Color.White)

    newGraphic.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias

    newGraphic.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic

    newGraphic.DrawImage(upBmp, newX, newY, newWidth, newHeight)

    newBmp.Save(MapPath(filePath), Imaging.ImageFormat.Png)

    'Show the uploaded resized picture in the image control

    Image1.ImageUrl = filePath

    Image1.Visible = True

    Catch ex As Exception

    lblError.Text = ex.ToString

    Finally

    upBmp.Dispose()

    newBmp.Dispose()

    newGraphic.Dispose()

    End Try

    Else

    lblError.Text = "Please select a picture with a file format extension of either Bmp, Jpg, Jpeg, Gif or Png."

    End If

    End If

    End Sub

    Function CheckFileType(ByVal fileName As String) As Boolean

    Dim ext As String = Path.GetExtension(fileName)

    Select Case ext.ToLower()

    Case ".gif"

    Return True

    Case ".png"

    Return True

    Case ".jpg"

    Return True

    Case ".jpeg"

    Return True

    Case ".bmp"

    Return True

    Case Else

    Return False

    End Select

    End Function

    End Class

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, March 11, 2007 6:23 PM
  • User60291871 posted

    Hi,

    Yes that does happen when its converted to C#.  Basically the problem in the C# code is with the data types used for the Reduce, UpWidth and UpHeight variables, resulting in a Reduce variable value of 0 most of the time. Changing the data type to Double for these variables solves the problem. There is another post with lots of threads an comments on my code here too: http://forums.asp.net/t/1079883.aspx?PageIndex=1

    Here's the working C# code: 

    using System;
    using System.IO;
    using System.Drawing;
    
    
    public partial class _Default : System.Web.UI.Page
    {
        
        public bool CheckFileType(string fileName) 
        { 
            
            string ext = Path.GetExtension(fileName); 
            
            switch (ext.ToLower()) { 
                
                case ".gif": 
                    
                    return true; 
                
                case ".png": 
                    
                    return true; 
                
                case ".jpg": 
                    
                    return true; 
                
                case ".jpeg": 
                    
                    return true; 
                
                case ".bmp": 
                    
                    return true; 
                
                default: 
                    
                    return false; 
                
            } 
            
        }
    
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            const int bmpW = 300;
            //New image target width 
    
            const int bmpH = 225;
            //New Image target height 
    
    
            if ((FileUpload1.HasFile))
            {
                //Clear the error label text 
    
                lblError.Text = "";
    
                //Check to make sure the file to upload has a picture file format extention and set the target width and height 
    
                if ((CheckFileType(FileUpload1.FileName)))
                {
    
                    Int32 newWidth = bmpW;
    
                    Int32 newHeight = bmpH;
    
                    //Use the uploaded filename for saving without the '.' extension 
    
                    String upName = FileUpload1.FileName.Substring(0, FileUpload1.FileName.IndexOf("."));
    
                    //Set the save path of the resized image, you will need this directory already created in your web site 
    
                    string filePath = "~/Upload/" + upName + ".jpg";
    
                    //Create a new Bitmap using the uploaded picture as a Stream 
    
                    //Set the new bitmap resolution to 72 pixels per inch 
    
                    Bitmap upBmp = (Bitmap)Bitmap.FromStream(FileUpload1.PostedFile.InputStream);
    
                    Bitmap newBmp = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
    
                    newBmp.SetResolution(72, 72);
    
                    //Get the uploaded image width and height 
    
                    Double upWidth = upBmp.Width;
    
                    Double upHeight = upBmp.Height;
    
                    int newX = 0;
                    //Set the new top left drawing position on the image canvas 
    
                    int newY = 0;
    
                    Double reDuce;
    
                    //Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions 
    
                    //to ensure the image is always in the centre of the canvas vertically and horizontally 
    
                    if (upWidth > upHeight)
                    {
                        //Landscape picture 
    
                        reDuce = newWidth / upWidth;
    
                        //calculate the width percentage reduction as decimal 
    
                        newHeight = ((Int32)(upHeight * reDuce));
    
                        //reduce the uploaded image height by the reduce amount 
    
                        newY = ((Int32)((bmpH - newHeight) / 2));
    
                        //Position the image centrally down the canvas 
    
                        newX = 0;
                        //Picture will be full width 
                    }
    
                    else if (upWidth < upHeight)
                    {
                        //Portrait picture 
    
                        reDuce = newHeight / upHeight;
    
                        //calculate the height percentage reduction as decimal 
    
                        newWidth = ((Int32)(upWidth * reDuce));
    
                        //reduce the uploaded image height by the reduce amount 
    
                        newX = ((Int32)((bmpW - newWidth) / 2));
    
                        //Position the image centrally across the canvas 
    
                        newY = 0;
                        //Picture will be full hieght 
                    }
    
                    else if (upWidth == upHeight)
                    {
                        //square picture 
    
                        reDuce = newHeight / upHeight;
    
                        //calculate the height percentage reduction as decimal 
    
                        newWidth = ((Int32)(upWidth * reDuce));
    
                        //reduce the uploaded image height by the reduce amount 
    
                        newX = ((Int32)((bmpW - newWidth) / 2));
                        //Position the image centrally across the canvas 
    
                        newY = ((Int32)((bmpH - newHeight) / 2));
                        //Position the image centrally down the canvas 
    
                    }
    
                    //Create a new image from the uploaded picture using the Graphics class 
    
                    //Clear the graphic and set the background colour to white 
    
                    //Use Antialias and High Quality Bicubic to maintain a good quality picture 
    
                    //Save the new bitmap image using 'Png' picture format and the calculated canvas positioning 
    
                    Graphics newGraphic = Graphics.FromImage(newBmp);
    
                    try
                    {
    
                        newGraphic.Clear(Color.White);
    
                        newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    
                        newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    
                        newGraphic.DrawImage(upBmp, newX, newY, newWidth, newHeight);
    
                        newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.Jpeg);
    
                        //Show the uploaded resized picture in the image control 
    
                        Image1.ImageUrl = filePath;
    
                        Image1.Visible = true;
                    }
    
                    catch (Exception ex)
                    {
    
                        string newError = ex.Message;
                        lblError.Text = newError;
                    }
    
                    finally
                    {
    
                        upBmp.Dispose();
    
                        newBmp.Dispose();
    
                        newGraphic.Dispose();
    
                    }
                }
    
                else
                {
    
                    lblError.Text = "Please select a picture with a file format extension of either Bmp, Jpg, Jpeg, Gif or Png.";
    
                }
    
            } 
        }
    } 
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 9, 2010 8:30 AM

All replies

  • User-846453637 posted

    check this

        // Get the path of the original Image
         string displayedImg = Server.MapPath("~") + "/Testing.jpg";

        // Get the path of the Thumb folder
        string displayedImgThumb = Server.MapPath("~") + "/Thumb/";
        
        // Get the original image file name
        string imgFileName = System.IO.Path.GetFileName(displayedImg);
     
        // Load original image
        System.Drawing.Image myimg = System.Drawing.Image.FromFile(displayedImg);

        // Get the thumbnail 100 X 100 px
        myimg = myimg.GetThumbnailImage(100, 100, null, IntPtr.Zero);
        
       // Save the new thumbnail image
       myimg.Save(displayedImgThumb + imgFileName, myimg.RawFormat);

    Hope this helps

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 9, 2007 2:52 PM
  • User60291871 posted

    Thanks Ramzi,

    This has pointed me in the right direction. I'm now looking at the Graphics class too, so that I can do more with the original image. Once I have the code working as I want, I'll post it here for anyone else to use.

     Regards Sean.[8-|]

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, March 11, 2007 7:32 AM
  • User60291871 posted

    Here's my VB code as promised. I'm a newbee to VWD and ASP.NET and know how hard it can be to find useful code. My code might not be elegant but it works well for me! Hope it helps someone else.

     

    Imports System.IO

    Imports System.Drawing

     

    Partial Class _Default

    Inherits System.Web.UI.Page

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click

    Const bmpW = 300 'New image canvas width

    Const bmpH = 226 'New Image canvas height

    If (FileUpload1.HasFile) Then

    lblError.Text = ""

    'Check to make sure the file to upload has a picture file format extention

    If (CheckFileType(FileUpload1.FileName)) Then

    Dim newWidth As Integer = bmpW

    Dim newHeight As Integer = bmpH

    'Use the uploaded filename without the '.' extension

    Dim upName As String = Mid(FileUpload1.FileName, 1, (InStr(FileUpload1.FileName, ".") - 1))

    Dim filePath As String = "~/Upload/" & upName & ".png"

    'Create a new Bitmap using the uploaded picture as a Stream

    'Set the new bitmap resolution to 72 pixels per inch

    Dim upBmp As Bitmap = Bitmap.FromStream(FileUpload1.PostedFile.InputStream)

    Dim newBmp As Bitmap = New Bitmap(newWidth, newHeight, Imaging.PixelFormat.Format24bppRgb)

    newBmp.SetResolution(72, 72)

    'Get the uploaded image width and height

    Dim upWidth As Integer = upBmp.Width

    Dim upHeight As Integer = upBmp.Height

    Dim newX As Integer = 0

    Dim newY As Integer = 0

    Dim reDuce As Decimal

    'Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions

    'to ensure the image is always in the centre of the canvas vertically and horizontally

    If upWidth > upHeight Then 'Landscape picture

    reDuce = newWidth / upWidth 'calculate the width percentage reduction as decimal

    newHeight = Int(upHeight * reDuce) 'reduce the uploaded image height by the reduce amount

    newY = Int((bmpH - newHeight) / 2) 'Position the image centrally down the canvas

    newX = 0 'Picture will be full width

    ElseIf upWidth < upHeight Then 'Portrait picture

    reDuce = newHeight / upHeight 'calculate the height percentage reduction as decimal

    newWidth = Int(upWidth * reDuce) 'reduce the uploaded image height by the reduce amount

    newX = Int((bmpW - newWidth) / 2) 'Position the image centrally across the canvas

    newY = 0 'Picture will be full hieght

    ElseIf upWidth = upHeight Then 'square picture

    reDuce = newHeight / upHeight 'calculate the height percentage reduction as decimal

    newWidth = Int(upWidth * reDuce) 'reduce the uploaded image height by the reduce amount

    newX = Int((bmpW - newWidth) / 2) 'Position the image centrally across the canvas

    newY = Int((bmpH - newHeight) / 2) 'Position the image centrally down the canvas

    End If

    'Create a new image from the uploaded picture using the Graphics class

    'Clear the graphic and set the background colour to white

    'Use Antialias and High Quality Bicubic to maintain a good quality picture

    'Save the new bitmap image using 'Png' picture format and the calculated canvas positioning

    Dim newGraphic As Graphics = Graphics.FromImage(newBmp)

    Try

    newGraphic.Clear(Color.White)

    newGraphic.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias

    newGraphic.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic

    newGraphic.DrawImage(upBmp, newX, newY, newWidth, newHeight)

    newBmp.Save(MapPath(filePath), Imaging.ImageFormat.Png)

    'Show the uploaded resized picture in the image control

    Image1.ImageUrl = filePath

    Image1.Visible = True

    Catch ex As Exception

    lblError.Text = ex.ToString

    Finally

    upBmp.Dispose()

    newBmp.Dispose()

    newGraphic.Dispose()

    End Try

    Else

    lblError.Text = "Please select a picture with a file format extension of either Bmp, Jpg, Jpeg, Gif or Png."

    End If

    End If

    End Sub

    Function CheckFileType(ByVal fileName As String) As Boolean

    Dim ext As String = Path.GetExtension(fileName)

    Select Case ext.ToLower()

    Case ".gif"

    Return True

    Case ".png"

    Return True

    Case ".jpg"

    Return True

    Case ".jpeg"

    Return True

    Case ".bmp"

    Return True

    Case Else

    Return False

    End Select

    End Function

    End Class

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, March 11, 2007 6:23 PM
  • User-140087699 posted

    Hi smcoxon ,

    Thanks for posting your code. I've developed/extended a C# method for handling aspect ratio's, however I am interested in the Interpolation and smoothing your code takes advantage of.
    After implementing the following lines from your code:
    <o:p></o:p>

    newGraphic.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
    newGraphic.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic<o:p></o:p>

    I dont see a difference in image quality for JPG and PNG images. Though simply choosing PNG output type produces notably better image quality (and a larger file size).<o:p></o:p>

    My question to you is if you are seeing a definite change in quality when resizing with image Interpolation and Smoothing?<o:p></o:p>

    Monday, January 7, 2008 9:17 AM
  • User60291871 posted

    Hi, I must confess I am not an expert on graphic images. I'm not surprised that you are not experiencing any difference with these two lines of codes though. AntiAlias is used in graphics applications for the smoothing of text and lines (diagonals and circles for example) and to help reduce wavy lines, bands or moiré patterns in images  HighQualityBicubic is an algorithm used when scaling images (Shrink or Stretch) to maintain reasonable image quality with respect to the original image. So depending on your original images these lines of code may or may not have an effect on the resized image quality. I leave them in just in case. Take a look at

    http://msdn.microsoft.com/en-us/library/a619zh6z.aspx

     http://msdn.microsoft.com/en-us/library/k0fsyd4e(VS.85).aspx

    Hope this helps answer your questions.

    Wednesday, January 9, 2008 7:04 AM
  • User-1125407041 posted

    Hi, Thank you for this Code, I have made some changes and its working very nicely in my application..

     Many Thanks To you

    Thursday, December 25, 2008 11:46 PM
  • User60291871 posted

    No problem, glad it helped you. Seems my piece of code has been extensively used by many people on this forum. Over 126,000 visits to my posts on this subject here:

    http://forums.asp.net/t/1079883.aspx

    Friday, December 26, 2008 7:37 AM
  • User-1046621233 posted

    Hey

    Just wanna say thank you for the code you have given us

    Its helping me alot

    Thanks so much

    Spider8990

    Wednesday, February 25, 2009 4:38 AM
  • User60291871 posted

    [cool] Glad it helps and thanks for showing your appriciation.

    smcoxon

    Wednesday, February 25, 2009 5:34 PM
  • User1991319095 posted

    This is brilliant.  Thanks for showing your code.  It has saved me TONS of time!

    Saturday, July 25, 2009 2:56 PM
  • User60291871 posted

     Your welcome.

    I'd love to know how many people are using this piece of code, with over 150,000 views must be quite a few! Surprised

    Tuesday, July 28, 2009 1:53 PM
  • User-460984998 posted

     Thanks for the post.

    Saved me lots of time....

    Cheers

    Wednesday, September 2, 2009 10:50 PM
  • User-962338856 posted

    Boy, was I glad I came across this post while I was looking for a way to reduce images before upload, but...

    While the code works fine, I found out that the reduced image is actually far larger in size than the original. Files that were originally around 70KB, become around 170KB after "reduction". I also tried saving as .jpg but to no avail. Kind of beats the whole purpose, I think. It's a pity, and I still have to find a way to reduce images.

    Sunday, September 20, 2009 11:27 AM
  • User60291871 posted

    Hmmm, not sure what's happening for you?

    I get file sizes of approx. 10-15Kb from a range of originals from 185Kb up to 1.5Mb using Jpg. The 10-15Kb is for an image reduced in size to 300x225 from an original of 2272 x 1712.

    Are you using 72x72 Pixels per Inch or have you changed this in your code? More PPI will result in bigger files for picture of the same size or even for a reduced image.

    I havent heard anyone else having an issue with the code creating larger images. Can you expalin exactly what you are doing in terms of the original picture file type, size and dimensions and the resulting picture file type, size and dimensions?

    Monday, September 21, 2009 7:14 AM
  • User-962338856 posted

    Hmmm, not sure what's happening for you?

    I get file sizes of approx. 10-15Kb from a range of originals from 185Kb up to 1.5Mb using Jpg. The 10-15Kb is for an image reduced in size to 300x225 from an original of 2272 x 1712.

    Are you using 72x72 Pixels per Inch or have you changed this in your code? More PPI will result in bigger files for picture of the same size or even for a reduced image.

    I havent heard anyone else having an issue with the code creating larger images. Can you expalin exactly what you are doing in terms of the original picture file type, size and dimensions and the resulting picture file type, size and dimensions?

     

    Well, like I said I just reduced the files, maintained the 72 ppi resolution, everything. Not being much experienced with graphics manipulation, I didn't bother too much finding out what's wrong, especially after I found this other routine elsewhere on this forum (sorry, lost the thread ref), which does exactly what I want:

    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
    intNewWidth = Convert.ToInt32(dblCoef * intOldWidth)
    intNewHeight = Convert.ToInt32(dblCoef * intOldHeight)
    Dim dblCoef As Double = MaxSideSize / CDbl(intMaxSide)
    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(MapPath(ImageSavePath), fmtImageFormat)
    'release used resources
    imgInput.Dispose()
    bmpResized.Dispose()
    Buffer.Close()
    End Sub

    This one reduced the same 70 kb image to 9 KB.

    Thanks anyway for your attention.

    Regards,

    Premy

    Wednesday, September 23, 2009 10:02 AM
  • User1176561268 posted

    Hi...

    You can use the following code..


    try
            {

                FileUpload1.SaveAs(Server.MapPath("~/CLogos/") + FileUpload1.FileName);

                // Get the path of the original Image
                string displayedImg = Server.MapPath("~/CLogos/") + FileUpload1.FileName;

                // Get the path of the Thumb folder
                string displayedImgThumb = Server.MapPath("~/CLogos/Thumbnail/");

                // Get the original image file name
                string imgFileName = System.IO.Path.GetFileName(displayedImg);

                // Load original image
                System.Drawing.Image myimg = System.Drawing.Image.FromFile(displayedImg);

                // Get the thumbnail 100 X 100 px
                myimg = myimg.GetThumbnailImage(100, 100, null, IntPtr.Zero);

                // Save the new thumbnail image
                myimg.Save(displayedImgThumb + imgFileName, myimg.RawFormat);

            }
            catch { }


    Mark AS Answer if useful..


    Thanks

    Kinjal

    Sharma Infoway

    Thursday, October 8, 2009 6:19 AM
  • User-962338856 posted

    Thank u for yr answer Kinjal, but like I pointed out in my previous post, I already found a routine which does exactly what I need. I'm sure yr code is worthwhile too, nevertheless.

    Regards,

    Premy 

    Tuesday, October 20, 2009 9:06 AM
  • User60291871 posted

    Hi,

    Thumbnails are exactly what they say they are... Thumbnails, smaller versions of the original and lower quality. With my example code you have the option of controlling the pixels per inch, colour depth etc. If all you want is small 'thumbnails' then using GetThumbnailImage is fine. 

    Tuesday, October 27, 2009 3:55 PM
  • User2065288525 posted
    Int16 bmpW = 300;
                Int16 bmpH = 226;
    
                if (FileUpload1.HasFile)
                {
                    lblError.Text = "";
    
                    Int16 newWidth = bmpW;
                    Int16 newHeight = bmpH;
                    string upName = FileUpload1.FileName;
    
                    string filepath = "~/images/" + upName + ".png";
    
                    Bitmap upBMP = (Bitmap)Bitmap.FromStream(FileUpload1.PostedFile.InputStream);
                    Bitmap newBMP = new Bitmap(newWidth,newHeight,System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    newBMP.SetResolution(72,72);
    
    
                    Int16 UpWidth = (Int16) upBMP.Width;
                    Int16 UpHeight = (Int16) upBMP.Height;
    
    
                    Int16 newX = 0;
                    Int16 newY = 0;
                    Decimal Reduce;
    
    
                    if (UpWidth>UpHeight) // landscape
                    {
                        Reduce=newWidth/UpWidth ;
                        newHeight = (Int16) (UpHeight * Reduce) ;
                        newY =(Int16)((bmpH - newHeight) /2);
    
                        newX=0;
                    }
                    else if (UpWidth < UpHeight) //portrait
                    {
                         Reduce=newWidth/UpHeight  ;
                        newWidth = (Int16) (UpWidth * Reduce) ;
                        newX= (Int16)((bmpW - newWidth) /2);
    
                        newY=0;
                    }
                    else if (UpWidth == UpHeight) // square pic
                    {
                        Reduce=newHeight/UpHeight  ;
                        newWidth = (Int16) (UpWidth * Reduce) ;
    
                        newX = (Int16)((bmpW - newWidth) /2);
                        newY =(Int16)((bmpH - newHeight) /2);
                    }
    
                    Graphics newGraphics = Graphics.FromImage(newBMP);
                    newGraphics.Clear(Color.White);
                    newGraphics.SmoothingMode=System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    newGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    
                    newGraphics.DrawImage(upBMP, (float)newX, (float)newY, newWidth, newHeight);
                    newBMP.Save(MapPath(filepath),System.Drawing.Imaging.ImageFormat.Png);
    
                   Image1.ImageUrl=filepath;
                    Image1.Visible=true;
    
                }
    


    hi smcoxon :(


    I have copied your entire code and its working in my sample  web page using vb.net but when i converted it into C# all i get is image with white color in it and not the one as it was working for vb.net code

    i spent nearly 2 hour looking for issue but cant figure out. the image generated is just a white block. check the code i used of yours in C#.net.


    plz help me. create a new asp.net prj wih C# as language and use the code below





    Saturday, January 9, 2010 4:42 AM
  • User60291871 posted

    Hi,

    Yes that does happen when its converted to C#.  Basically the problem in the C# code is with the data types used for the Reduce, UpWidth and UpHeight variables, resulting in a Reduce variable value of 0 most of the time. Changing the data type to Double for these variables solves the problem. There is another post with lots of threads an comments on my code here too: http://forums.asp.net/t/1079883.aspx?PageIndex=1

    Here's the working C# code: 

    using System;
    using System.IO;
    using System.Drawing;
    
    
    public partial class _Default : System.Web.UI.Page
    {
        
        public bool CheckFileType(string fileName) 
        { 
            
            string ext = Path.GetExtension(fileName); 
            
            switch (ext.ToLower()) { 
                
                case ".gif": 
                    
                    return true; 
                
                case ".png": 
                    
                    return true; 
                
                case ".jpg": 
                    
                    return true; 
                
                case ".jpeg": 
                    
                    return true; 
                
                case ".bmp": 
                    
                    return true; 
                
                default: 
                    
                    return false; 
                
            } 
            
        }
    
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            const int bmpW = 300;
            //New image target width 
    
            const int bmpH = 225;
            //New Image target height 
    
    
            if ((FileUpload1.HasFile))
            {
                //Clear the error label text 
    
                lblError.Text = "";
    
                //Check to make sure the file to upload has a picture file format extention and set the target width and height 
    
                if ((CheckFileType(FileUpload1.FileName)))
                {
    
                    Int32 newWidth = bmpW;
    
                    Int32 newHeight = bmpH;
    
                    //Use the uploaded filename for saving without the '.' extension 
    
                    String upName = FileUpload1.FileName.Substring(0, FileUpload1.FileName.IndexOf("."));
    
                    //Set the save path of the resized image, you will need this directory already created in your web site 
    
                    string filePath = "~/Upload/" + upName + ".jpg";
    
                    //Create a new Bitmap using the uploaded picture as a Stream 
    
                    //Set the new bitmap resolution to 72 pixels per inch 
    
                    Bitmap upBmp = (Bitmap)Bitmap.FromStream(FileUpload1.PostedFile.InputStream);
    
                    Bitmap newBmp = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
    
                    newBmp.SetResolution(72, 72);
    
                    //Get the uploaded image width and height 
    
                    Double upWidth = upBmp.Width;
    
                    Double upHeight = upBmp.Height;
    
                    int newX = 0;
                    //Set the new top left drawing position on the image canvas 
    
                    int newY = 0;
    
                    Double reDuce;
    
                    //Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions 
    
                    //to ensure the image is always in the centre of the canvas vertically and horizontally 
    
                    if (upWidth > upHeight)
                    {
                        //Landscape picture 
    
                        reDuce = newWidth / upWidth;
    
                        //calculate the width percentage reduction as decimal 
    
                        newHeight = ((Int32)(upHeight * reDuce));
    
                        //reduce the uploaded image height by the reduce amount 
    
                        newY = ((Int32)((bmpH - newHeight) / 2));
    
                        //Position the image centrally down the canvas 
    
                        newX = 0;
                        //Picture will be full width 
                    }
    
                    else if (upWidth < upHeight)
                    {
                        //Portrait picture 
    
                        reDuce = newHeight / upHeight;
    
                        //calculate the height percentage reduction as decimal 
    
                        newWidth = ((Int32)(upWidth * reDuce));
    
                        //reduce the uploaded image height by the reduce amount 
    
                        newX = ((Int32)((bmpW - newWidth) / 2));
    
                        //Position the image centrally across the canvas 
    
                        newY = 0;
                        //Picture will be full hieght 
                    }
    
                    else if (upWidth == upHeight)
                    {
                        //square picture 
    
                        reDuce = newHeight / upHeight;
    
                        //calculate the height percentage reduction as decimal 
    
                        newWidth = ((Int32)(upWidth * reDuce));
    
                        //reduce the uploaded image height by the reduce amount 
    
                        newX = ((Int32)((bmpW - newWidth) / 2));
                        //Position the image centrally across the canvas 
    
                        newY = ((Int32)((bmpH - newHeight) / 2));
                        //Position the image centrally down the canvas 
    
                    }
    
                    //Create a new image from the uploaded picture using the Graphics class 
    
                    //Clear the graphic and set the background colour to white 
    
                    //Use Antialias and High Quality Bicubic to maintain a good quality picture 
    
                    //Save the new bitmap image using 'Png' picture format and the calculated canvas positioning 
    
                    Graphics newGraphic = Graphics.FromImage(newBmp);
    
                    try
                    {
    
                        newGraphic.Clear(Color.White);
    
                        newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    
                        newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    
                        newGraphic.DrawImage(upBmp, newX, newY, newWidth, newHeight);
    
                        newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.Jpeg);
    
                        //Show the uploaded resized picture in the image control 
    
                        Image1.ImageUrl = filePath;
    
                        Image1.Visible = true;
                    }
    
                    catch (Exception ex)
                    {
    
                        string newError = ex.Message;
                        lblError.Text = newError;
                    }
    
                    finally
                    {
    
                        upBmp.Dispose();
    
                        newBmp.Dispose();
    
                        newGraphic.Dispose();
    
                    }
                }
    
                else
                {
    
                    lblError.Text = "Please select a picture with a file format extension of either Bmp, Jpg, Jpeg, Gif or Png.";
    
                }
    
            } 
        }
    } 
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, January 9, 2010 8:30 AM
  • User2065288525 posted

    thanks a lot again.

    Monday, January 11, 2010 4:00 PM
  • User1211441112 posted

    public static void ResizeStream(int imageSize, Stream filePath, string outputPath)
    {

                var image = Image.FromStream(filePath);
                int thumbnailSize = imageSize;
                int newWidth, newHeight;

                if (image.Width > image.Height)
                {
                    newWidth = thumbnailSize;
                    newHeight = image.Height * thumbnailSize / image.Width;
                }
                else
                {
                    newWidth = image.Width * thumbnailSize / image.Height;
                    newHeight = thumbnailSize;
                }


                var thumbnailBitmap = new Bitmap(newWidth, newHeight);
                var thumbnailGraph = Graphics.FromImage(thumbnailBitmap);

                thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
                thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
                thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

                var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
                thumbnailGraph.DrawImage(image, imageRectangle);


                thumbnailBitmap.Save(toStream, image.RawFormat);


                thumbnailGraph.Dispose();
                thumbnailBitmap.Dispose();
                image.Dispose();
    }

    Thursday, January 14, 2010 12:31 AM
  • User-1772065905 posted

    Hi,


    I'm using a VB coding and VB image resize. I have a question. If in case "ElseIf upWidth < upHeight Then" then middle of the picture and the white is going well. How can i fix this problem ?

    Wednesday, June 9, 2010 11:12 AM
  • User60291871 posted

    Hi,

    I'm not sure I understand your problem but as in the C# version, try changing the data types for the Reduce, UpWidth and UpHeight variables to Double. 

    Friday, June 11, 2010 3:15 PM
  • User647540711 posted

    Thanks ?smcoxon, very nice example. I would like to clarify one point.

    Your comment on Line 169:
    //Save the new bitmap image using 'Png' picture format and the calculated canvas positioning

    Your code on line 184:
    newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.Jpeg);

    Should it not be "System.Drawing.Imaging.ImageFormat.Png" or am I missing something?

    Monday, June 14, 2010 7:39 PM
  • User60291871 posted

     Hi,

    You can save the image in .Png, .Jpeg and other formats.

    What you have noticed is my comment in the code doesn't match up with the image file type being used in the code at line 184. I probably changed the code to save the image as a Jpeg at sometime in the past but didnt change the comment to match. As comments are just comments they don't effect the code at run time. Use and change the code and comments to suit your needs.

    Monday, June 14, 2010 8:07 PM
  • User-861155893 posted

    I think his 'compression problem' comes from not applying compression. I'm no expert but have had this issue and I think its because the GDI object you are using is Bitmap (uncompressed) and no JPEG encoding compression is applied after the GDI creation of the thumb (just scanned your code so please forgive if I missed)... anyway. 

    I use a couple of methods for this and it applies JPEG compression etc

        private static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
        {
            Bitmap bmpOut = null;
            try
            {
                Bitmap loBMP = new Bitmap(lcFilename);
                ImageFormat loFormat = loBMP.RawFormat;
                decimal lnRatio;
                int lnNewWidth = 0;
                int lnNewHeight = 0;
    
                //*** If the image is smaller than a thumbnail just return it
                if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
                    return loBMP;
    
                if (loBMP.Width > loBMP.Height)
                {
                    lnRatio = (decimal)lnWidth / loBMP.Width;
                    lnNewWidth = lnWidth;
                    decimal lnTemp = loBMP.Height * lnRatio;
                    lnNewHeight = (int)lnTemp;
                }
                else
                {
                    lnRatio = (decimal)lnHeight / loBMP.Height;
                    lnNewHeight = lnHeight;
                    decimal lnTemp = loBMP.Width * lnRatio;
                    lnNewWidth = (int)lnTemp;
                }
                // System.Drawing.Image imgOut =
                //      loBMP.GetThumbnailImage(lnNewWidth,lnNewHeight,
                //                              null,IntPtr.Zero);
                // *** This code creates cleaner (though bigger) thumbnails and properly
                // *** and handles GIF files better by generating a white background for
                // *** transparent images (as opposed to black)
    
                bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
                Graphics g = Graphics.FromImage(bmpOut);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
    
                g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
                loBMP.Dispose();
            }
            catch
            {
                return null;
            }
            return bmpOut;
        }
    


    and the compression/codec grabbing methods

        public static string CreateImageThumbnail(string filename, long compression)
        {
            Bitmap bmp = CreateThumbnail(HttpContext.Current.Server.MapPath(Constants.UploadPath + filename), Constants.thumbDim, Constants.thumbDim);
            try
            {
                //Parameter object to compress the image
                // this automatically converts to jpeg of n compression
                ImageCodecInfo codec = GetEncoder(ImageFormat.Jpeg);
                Encoder enc = Encoder.Quality;
                EncoderParameters prms = new EncoderParameters(1);
                prms.Param[0] = new EncoderParameter(enc, compression);
    
                bmp.Save(HttpContext.Current.Server.MapPath(Constants.UploadPath + Constants.thumbPrefix + filename), codec, prms);
                return Constants.thumbPrefix + filename;
            }
    
            catch (Exception ex)
            {
                bmp.Dispose();
                return filename;
            }
        }
    
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
    
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
    
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }


    Monday, June 14, 2010 8:17 PM
  • User647540711 posted

    I wasn't picking nits with your code (or comments) Smcoxon, just wanted to confirm that newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.<Png | Jpeg | Gif >); would all work; i.e. if I start with an uploaded (larger) jpg and I resize it I can then save it as a Png or vice versa. Makes sense given that we have a bitmap as an intermediate format but I have always done a "same format" resize - force of habit.

    Thanks again for your well documented example.

    Monday, June 14, 2010 10:50 PM
  • User60291871 posted

    Hi,

    I didn't think you were nit picking, sorry if my response gave you that impression. Yes you can save in Png | Jpeg | Gif image formats. Just test it out first as you may get some un-expected results. I.e. GIF is not very good for photographic images.

    Cheers!

    Tuesday, June 15, 2010 4:34 AM
  • User963478053 posted

    Hello,

    Awesome tutorial.

    Could you provide any help on how can i save the newly resized image in an SQL Server 2008 database.


    Thanks a lot

    Thursday, June 17, 2010 8:05 PM
  • User647540711 posted

    I can provide the ADO.NET code but there are simpler ways of doing it. I'll wait to see if someone (smarter than me no doubt) answers your question and if not I'll post my code. 

    Thursday, June 17, 2010 8:31 PM
  • User963478053 posted

    Any help would be appreciated :D

    Thursday, June 17, 2010 8:52 PM
  • User963478053 posted

    I can provide the ADO.NET code but there are simpler ways of doing it. I'll wait to see if someone (smarter than me no doubt) answers your question and if not I'll post my code. 


    Could you provide your solution until someone fiinds an easier way?

    I'm trying to save the resized image to the database using the filepath but it doesn't work :(

    FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
                            byte[] data = new byte[fs.Length];
                            fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
                            fs.Close();

    FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
                            byte[] data = new byte[fs.Length];
                            fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
                            fs.Close();



    Friday, June 18, 2010 9:44 AM
  • User647540711 posted

    This may raise more questions than it answers but …

    I can’t provide all the code you need to run this so hopefully you will be able to extrapolate from what I can provide. There is to the greatest degree possible a separation of concerns. The structure is as follows:

    The presentation layer passes the uploaded image to a class that handles the resizing:

    byte[] profileImage = public static Byte[] ScaledImageByteSmall(HttpPostedFile uploadedImage, int maxHeight, int maxWidth, string fileExt);

    The byte array is then passed to the ADO.NET data access layer:

    bool profileUpdated = UserProfile.UpdateUserPhoto(fileType, profileImage);

            /// <summary>

            /// Updates a user profile photo

            /// This is probably specific to SQL Server - haven't researched it

            /// </summary>

            public static bool UpdateUserPhoto(string photoFileType, Byte[] photo)

            {

                // get a configured DbCommand object

                DbCommand comm = GenericDataAccess.CreateCommand();

                // set the stored procedure name

                comm.CommandText = "user_Profile_Photo_Update";

                // create a new parameter

                DbParameter param = comm.CreateParameter();

                param.ParameterName = "@UserId";

                param.Value = UserId;

                param.DbType = DbType.String;

                param.Size = 36;

                comm.Parameters.Add(param);

                // create a new parameter

                param = comm.CreateParameter();

                param.ParameterName = "@PhotoFileType";

                param.Value = photoFileType;

                param.DbType = DbType.String;

                param.Size = 10;

                comm.Parameters.Add(param);

                // create a new parameter

                param = comm.CreateParameter();

                param.ParameterName = "@Photo";

                param.Value = photo;

                // We don't set a DbType for SQL Server

                comm.Parameters.Add(param);

                // Execute the sproc

                int result = -1;

                try

                {

                    // execute the stored procedure

                    result = GenericDataAccess.ExecuteNonQuery(comm);

                }

                catch

                {

                       // The GenericDataAccess class handles exceptions and closes the database connection

                }

                // result will be 1 in case of success

                return (result != -1);

            }

     

    On the database side the sproc handles the update:

    ALTER PROCEDURE [dbo].[user_Profile_Photo_Update] 

    (

          @UserId                 UNIQUEIDENTIFIER,

          @PhotoFileType    VARCHAR(10),

          @Photo                  IMAGE

    )

    AS

    DECLARE @LastUpdatedDate      DATETIME

    SELECT @LastUpdatedDate = GetDate()

    BEGIN

    UPDATE dbo.user_Profile

    SET

          PhotoFileType = @PhotoFileType,

          Photo = @Photo,

          LastUpdatedDate = @LastUpdatedDate 

    WHERE UserId = @UserId

    END

    Friday, June 18, 2010 9:49 AM
  • User60291871 posted

    Hi,

    The first thing you need to decide is if to store the images in an SQL database or simply save it to a folder on yor web server. Both have their own merits.

    Saving to a folder is simple to do and if you are using a hosted service it doesn't use up lots of your valuable (costly) SQL server storage space. All you need to store in the database table is the url of the saved image (some thing like  "~/uploads/images/myimage.jpg") in a varchar field. It may also be quicker to retrive and display your image from the web server folder rather than having to make a read request from the SQL server.

    On the other hand, saving your image in the database ensures all your website data is held in one place - on the SQL server. Also, when you save/backup your database you will also save/backup all the associated images. There's less risk of someone overwiting or deleting your saved images as they are in the database not in a disk folder. And it maybe easier to maintain depending on your website and SQL data structure.

    In the end the choice is yours.

    There's lots of tutorials, blogs etc on how to save images in an SQL database. Take a look at this post to find a number of suggested links: http://forums.asp.net/p/1540957/3753998.aspx#3753998

     

    Friday, July 2, 2010 11:19 AM
  • User1667636013 posted

    Thanks for the code.

    I converted the code to C# and wanted to post but I noticed somone already did it. I was getting the same issue with the white background picture, til I realized that the integer divisions of height and width does not convert to decimal by default.

    In C#, you can either change the upHieght, upWidth and reDuce to double type or you can just use "Decimal.Divide(int, int)" prototype to divide integers to give you a decimal output.

    TIL .NET has a Graphics library.

    Thanks, again.

    Tuesday, March 15, 2011 11:54 AM
  • User60291871 posted

    Great, glad you found the code useful.

    smcoxon

    Wednesday, March 16, 2011 6:55 AM
  • User-139922747 posted

    Hi smcoxon from spain, i'm looking exactly for the same thing but in C#. Anyone with ANY answer suggest to show me the way to start is highly apreciated! bozzo

    Thursday, August 18, 2011 11:04 AM
  • User-451735805 posted

    Here's my VB code as promised

    Smcoxon,

    Your code worked great, but I had to change one thing, I had to replace "newX" and "newY" with the hard-coded values of 0. Otherwise I would get a thin white line along the bottom and left of my resized images.

    I spent ages puzzling over what the purpose was of the newX and newY, I never worked it out and then when I removed them and replaced them with 0s the white lines dissapeared.

    Also, I am using your code to resize all kinds of image types (jpg, gif, etc) and if the user uploads a jpg I leave it as a jpg extension, even though it uses "Imaging.ImageFormat.Png". Is that OK or is that wrong?

    Thursday, August 18, 2011 8:57 PM
  • User60291871 posted

    Hi bozzo,

    You can see a C# version of my code further back in this post on page 3.

    Tuesday, August 23, 2011 6:00 PM
  • User60291871 posted

    Hi TonyLoco23,

    If you look at my code the first thing set up is the canvas size - the size you want the resized image to be. This is usually a landscape orientation with a 4:3 (width:height) aspect ratio. When the original image is reduced, depending on its original dimensions, it may or may not be an exact 4:3 ratio. Therefore, to position the resized image centrally (horizontal and vertical) on the canvas, the newX and newY values are used as coordinates for the new top left position of the resized image on the canvas. This is done because you never know what the size and aspect ratio the original image will be. The white lines you see is because the canvas colour is set to white and the resized image is not always exactly the base canvas size, especially if the original image aspect ratio is to be maintained, as it is in my code to eliminate image distortion, or if a portrait image (3:4) is uploaded, resized and drawn on to the 4:3 canvas.

    An alternative approach would be to resize the base canvas size to match the exact dimensions of the resized image for every resized image. The issue with this is you will end up with images of different dimensions which makes your aspx page layout more of an issue when displaying the resized images.

    You can also change the canvas colour if you want to by changing the following line of code to the colour you want:

    newGraphic.Clear(Color.White)

    For the image types, I'm no graphics expert but I'd convert and save with the correct image type and file extention. Since posting my original code I convert and save all my images as Jpg. To do this change the line of code for the save filePath and the code that saves the image as follows:

    Dim filePath As String = "~/Upload/" & upName & ".jpg"
    
    newBmp.Save(MapPath(filePath), Imaging.ImageFormat.Jpeg)
    

    Wednesday, August 24, 2011 7:23 AM
  • User-1679916991 posted

    Yours is the closest I've gotten to finding something that works.  I have the code in place in my program with necessary name changes (destination folder and FileUpload object).  Stepped thru it in debug with great expectations only to find it errored at this line:

    newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.Jpeg);

    with this message: "A generic error occurred in GDI+"

    It was a 2MB jpg file, nothing weird.  Please help as I have no idea what to do to fix this.  Thanks!

    Saturday, August 27, 2011 9:14 AM
  • User60291871 posted

    The code looks correct. The error you have could be due to not having write permissions on the directory where you are trying to save the resized image file or maybe you are saving the resized image with the same name as the original file in to the same directory? Take a look at the following blogs and forum post:

    http://weblogs.asp.net/anasghanem/archive/2009/02/28/solving-quot-a-generic-error-occurred-in-gdi-quot-exception.aspx

    http://www.blog.vishalon.net/index.php/bitmapsave-a-generic-error-occurred-in-gdi

    http://forums.asp.net/t/624305.aspx

    Saturday, August 27, 2011 10:28 AM
  • User-1679916991 posted

    Neither is the case because (a) it the same upload folder the application currently uploads successfully to and (b) I have code before the "save" that checks whether the file name exists.

    csPath = Server.MapPath("AcftInspPhotos"); (done in Page_Load)
    DirectoryInfo dirInfoEx = new DirectoryInfo(@csPath);
    System.IO.FileInfo[] fileNamesEx = dirInfoEx.GetFiles(FileUpload_R1.FileName);
    if (fileNamesEx.GetLength(0) == 0)
    {
    (clipped)
    }

    Again, I emphasize this is a working program that already uploads aircraft discrepancy photos that were resized enmass prior to the upload.  Now my boss wants the user to skip the resize step and be able to select the fullsize photo and my program to resize it as it uploads.   So I've just inserted your code in my program.  Folder permissions were already in place. 

    I suspected it is the way the path is being used and I've tried

    changing this line
    newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.Jpeg);
    
    to this
    newBmp.Save(@csPath, System.Drawing.Imaging.ImageFormat.Jpeg);

    However, nothing I've tried so far solves this problem.  I know it's Saturday but if a lightbulb goes off in your head, please let me know.  I will go slowly thru the blog you cited and keep trying stuff.  Thanks!

     

    Saturday, August 27, 2011 11:26 AM
  • User-1679916991 posted

    I FIGURED IT OUT!!  I had to change this

    string filePath = "~/AcftInspPhotos/" + upName + ".jpg";

    to this

    string filePath = "~\\HR\\AcftInspPhotos\\" + upName + ".jpg";

    Even though both the running program AND the upload folder are already under the "HR" folder!

    Saturday, August 27, 2011 11:48 AM
  • User60291871 posted

    Excellent, glad you got it working for your website. Cool

    Saturday, August 27, 2011 12:45 PM