Click here to Skip to main content
15,890,186 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi Friends,
I am using a fileupload control in mvc4 ...... What i need is that i should convert all .bmp image files , .png image files ,.gif image files etc ....... all to .Jpeg Files .. And After converting to .jpeg files if it is less than 4 MB i should save it into database/Application path ........ And when it is more than 4 mb i should compress it and save it as .jpeg files ...... can anyone give me a sample
Posted
Updated 22-Sep-13 23:51pm
v2

1 solution

You can try this so compress image into specific size
C#
if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files[0];
                if (file != null && file.ContentLength > 0)
                {
                    string path = Path.GetFileName(file.FileName) + ".jpeg";

                    string saveFilePath = Path.Combine(Server.MapPath("/Images/"), path);

                    // Resize Image
                    if ((file.ContentLength / 1024) > 4096)
                    {
                        var newSize = new Size(100, 100);

                        using (var originalImage = System.Drawing.Image.FromFile(file.FileName))
                        {
                            using (var newImage = new Bitmap(newSize.Width, newSize.Height))
                            {
                                using (var canvas = Graphics.FromImage(newImage))
                                {
                                    canvas.SmoothingMode = SmoothingMode.AntiAlias;
                                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                    canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                                    canvas.DrawImage(originalImage, new System.Drawing.Rectangle(new Point(0, 0), newSize));
                                    newImage.Save(saveFilePath, originalImage.RawFormat);
                                }
                            }
                        }
                    }
                    else
                    {
                        file.SaveAs(saveFilePath);
                    }
                }
            }
 
Share this answer
 
v2
Comments
MurugappanCTS 24-Sep-13 6:08am    
thanks pooja

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900