views:

7721

answers:

12

I have an aspx page which will upload images to server harddisk from client pc

But now i need to change my program in such a way that it would allow me to resize the image while uploading.

Does anyone has any idea on this ? I couldnt not find such properties/methods with Input file server control

Any one there to guide me ?

A: 

can you explain what it is that you are trying to achieve by resizing before uploading? Are you trying to downasample the image or just resize to a different dimension?

+3  A: 

You will not be able to resize "on the fly" since you will need to have the full image before you perform any image transformations. However, after the upload is complete and before you display any results to your user, you can use this basic image resizing method that I've used in a couple of my apps now:

   ''' <summary>
   '''    Resize image with GDI+ so that image is nice and clear with required size.
   ''' </summary>
   ''' <param name="SourceImage">Image to resize</param>
   ''' <param name="NewHeight">New height to resize to.</param>
   ''' <param name="NewWidth">New width to resize to.</param>
   ''' <returns>Image object resized to new dimensions.</returns>
   ''' <remarks></remarks>
   Public Shared Function ImageResize(ByVal SourceImage As Image, ByVal NewHeight As Int32, ByVal NewWidth As Int32) As Image

      Dim bitmap As System.Drawing.Bitmap = New System.Drawing.Bitmap(NewWidth, NewHeight, SourceImage.PixelFormat)

      If bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format1bppIndexed Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format4bppIndexed Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format8bppIndexed Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Undefined Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.DontCare Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppArgb1555 Or _
          bitmap.PixelFormat = Drawing.Imaging.PixelFormat.Format16bppGrayScale Then
         Throw New NotSupportedException("Pixel format of the image is not supported.")
      End If

      Dim graphicsImage As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(bitmap)

      graphicsImage.SmoothingMode = Drawing.Drawing2D.SmoothingMode.HighQuality
      graphicsImage.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
      graphicsImage.DrawImage(SourceImage, 0, 0, bitmap.Width, bitmap.Height)
      graphicsImage.Dispose()
      Return bitmap

   End Function
Dillie-O
+1 for pointing out that image resizing must be done after entire image has been uploaded.
quakkels
+4  A: 

Once the file has been saved to the server you can use code like this to resize. This code will take care of length/width ratio on the resize.

public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
{

    System.Drawing.Bitmap bmpOut = null;

    try
    {
        Bitmap loBMP = new Bitmap(lcFilename);
        ImageFormat loFormat = loBMP.RawFormat;

        decimal lnRatio;
        int lnNewWidth = 0;
        int lnNewHeight = 0;

        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;
        }


        bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
        Graphics g = Graphics.FromImage(bmpOut);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
        g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);

        loBMP.Dispose();
    }
    catch
    {
        return null;
    }
    return bmpOut;
}
JPrescottSanders
A bit OT from the question, but how well does this handle low res images? I always end up getting malformed images with mine.
Tim Meers
I have generally been pushing high res images through that code so I can't give you a good answer there. It's honestly pretty easy to hook into an app and test so you might want to just give it a try, I don't think it will cost you a significant amount of time.
JPrescottSanders
A: 

using System.IO; using System.Drawing; using System.Drawing.Imaging;

public partial class admin_AddPhoto : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {

    string reportPath = Server.MapPath("../picnic");

    if (!Directory.Exists(reportPath))
    {
        Directory.CreateDirectory(Server.MapPath("../picnic"));
    }
}

protected void PhotoForm_ItemInserting(object sender, FormViewInsertEventArgs e)
{
    FormView uploadForm = sender as FormView;
    FileUpload uploadedFile = uploadForm.FindControl("uploadedFile") as FileUpload;

    if (uploadedFile != null)
    {
        string fileName = uploadedFile.PostedFile.FileName;
        string pathFile = System.IO.Path.GetFileName(fileName);

        try
        {
            uploadedFile.SaveAs(Server.MapPath("../picnic/") + pathFile);
        }
        catch (Exception exp)
        {
            //catch exception here
        }

        try
        {
            Bitmap uploadedimage = new Bitmap(uploadedFile.PostedFile.InputStream);

            e.Values["ImageWidth"] = uploadedimage.Width.ToString();
            e.Values["ImageHeight"] = uploadedimage.Height.ToString();
            // Make output File Name
            char[] splitter = { '.' };
            string[] splitFile = pathFile.Split(splitter);
            string OutputFilename = splitFile[0] + "s";

            System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            System.Drawing.Image thumbImage = uploadedimage.GetThumbnailImage(74, 54, myCallback, IntPtr.Zero);
            thumbImage.Save(Server.MapPath("../picnic/") + OutputFilename + ".jpg");
            e.Values["Thumbnail"] = "./picnic/" + OutputFilename + ".jpg";
        }
        catch (Exception ex)
        {
            //catch exception here
        }

        e.Values["Pic"] = "./picnic/" + pathFile;
        e.Values["Url"] = "./picnic/" + pathFile;
        e.Values["dateEntered"] = DateTime.Now.ToString();
    }
}

public bool ThumbnailCallback()
{
    return false;
}

}

This uses a FileUpload and a FormView to insert. Then I use the GetThumnailImage() method provided in System.Drawing.Imaging. You can enter any Width and Height values and it will shrink/stretch accordingly.

uploadedimage.GetThumbnailImage(W, H, myCallback, IntPtr.Zero);

Hope this helps.

Sean
A: 

You could resize before sending to the server using an ActiveX control. There is a free ASP.net image uploading component (I believe this is the same one that Facebook actually uses) available here:

http://forums.aurigma.com/yaf_postst2145_Image-Uploader-ASPNET-Control.aspx

Let me know if it works, I am thinking about implementing it in my projects here at work.

Edit: Looks like the wrapper for the object is free, however the actual component itself is going to run you about $200. I confirmed it is the same component Facebook is using though.

Kyle B.
A: 

Thank you all . If I am using the file upload control in ASP.NET,Its OK.I can browse it from the Local PC. But I want the users to enter a valid imageURL and let the system read it and upload it to server

How can i do this

?

Writing your own question in StackOverflow ;)
Leandro López
A: 

You'll need to use the WebClient class to download the remote image.

After that, then you can resize it...Use DrawImage, not GetThumbnailImage. Make sure you dispose of your bitmap and graphics handles.. (use using{}). Set all quality settings to high.

You might want to take a look at the source code for my popular image resizer first... It will help you avoid some common trouble areas. I also build customized versions for an additional $95.

+1  A: 
//Here is another WAY fox!!! i have actually modify the code from You all. HIHI
//First, add one textBox and one FileUpload Control, and a button

//paste this in your code behind file... after public partial class admin : System.Web.UI.Page

    string OriPath;
    string ImageName;

public Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)
    {
        Size NewSize;
        double tempval;

        if (OriginalHeight > FormatSize && OriginalWidth > FormatSize)
        {
            if (OriginalHeight > OriginalWidth)
                tempval = FormatSize / Convert.ToDouble(OriginalHeight);
            else
                tempval = FormatSize / Convert.ToDouble(OriginalWidth);

            NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight));
        }
        else
            NewSize = new Size(OriginalWidth, OriginalHeight); return NewSize;
    } 



//Now, On Button click add the folwing code.

if (FileUpload1.PostedFile != null)
        {
           ImageName = TextBox1.Text+".jpg";


           OriPath = Server.MapPath("pix\\") + ImageName;

           //Gets the Full Path using Filecontrol1 which points to actual location in the hardisk :)

           using (System.Drawing.Image Img = System.Drawing.Image.FromFile(System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName)))
           {
               Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, 800);

               using (System.Drawing.Image ImgThnail = new Bitmap(Img, ThumbNailSize.Width, ThumbNailSize.Height))
               {
                   ImgThnail.Save(OriPath, Img.RawFormat);
                   ImgThnail.Dispose();
               }
               Img.Dispose();
           }
}


//Enjoy. If any problem,, mail me at [email protected] 
+1  A: 

To resize down a image and get smaller sizes just make the changes below

    bmpOut = new Bitmap(lnNewWidth, lnNewHeight, **System.Drawing.Imaging.PixelFormat.Format24bppRgb**);

     Graphics g = Graphics.FromImage(bmpOut);

as you above a set the imagem to Format24bppRgb PixelFormat.

and when you save the file, you set the ImageFormat also. Like this:

bmpOut.Save(PathImage, System.Drawing.Imaging.ImageFormat.Jpeg);
+1  A: 

You can use this, it does a dandy job for me. But it does not handle low res images well for me. Thankfully I down use to many of them. Just sent it the image byte[] and the expected output and you'll be good to go.

public static byte[] ResizeImageFile(byte[] imageFile, int targetSize) 
{ 
    using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile))) 
    { 
        Size newSize = CalculateDimensions(oldImage.Size, targetSize); 

        using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) 
        { 
            newImage.SetResolution(oldImage.HorizontalResolution, oldImage.VerticalResolution); 
            using (Graphics canvas = Graphics.FromImage(newImage)) 
            { 
                canvas.SmoothingMode = SmoothingMode.AntiAlias; 
                canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; 
                canvas.PixelOffsetMode = PixelOffsetMode.HighQuality; 
                canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize)); 
                MemoryStream m = new MemoryStream(); 
                newImage.Save(m, ImageFormat.Jpeg); 
                return m.GetBuffer(); 
            } 
        } 

    } 
} 

private static Size CalculateDimensions(Size oldSize, int targetSize) 
{ 
    Size newSize = new Size(); 
    if (oldSize.Width > oldSize.Height) 
    { 
        newSize.Width = targetSize; 
        newSize.Height = (int)(oldSize.Height * (float)targetSize / (float)oldSize.Width); 
    } 
    else 
    { 
        newSize.Width = (int)(oldSize.Width * (float)targetSize / (float)oldSize.Height); 
        newSize.Height = targetSize; 
    } 
    return newSize; 
} 
Tim Meers
+1  A: 

Another approach would to allow the user to adjust the size in the browser and then resize the image as described in other answers.

So take a look at this solution which allows you to upload and crop images with jQuery, jCrop & ASP.NET.

Naeem Sarfraz
A: 

Why dont you use some swf uploader which can manupilate the image before uploading

HamdiKavak