locked
How resize and save image in one folder RRS feed

  • Question

  • User-257070954 posted

    Hi all
    How to take all images from one folder and reduce size and save to another folder in c#?

    Wednesday, August 1, 2018 4:40 AM

Answers

  • User-893317190 posted

    Hi binustrat ,

    I suggest you could use a utility class to  help you resize your image  more easily.

    I have created an example:
    This class contains four modes which could resize the image by height or width.

     The first mode named “HW”  is to  resize the image according the width and height specified ,which may cause distortion

     

    The second mode named “H” is to resize the image according to the height.

     

    The third mode named “W” is to resize the image according to the width .

     

    The fourth mode  named “Cut” is to resize the image according to the width and height specified which doesn’t  cause distortion.

     

     
    Below is my code.

    // get the absolute path of the original folder
                string path = Server.MapPath("~/Format/imageTest");
                // get all the absolute pathes  of files in the original folder
               string[] images= Directory.GetFiles(path);
                //get the absolute path of the targeted folder
               string target= Server.MapPath("~/Format/imageTarget");
                //initialize the util class
                ResizePicture resizePicture = new ResizePicture();
                //loop through the  pathes
               foreach (var item in images)
                {
                  
                
                    // the first argument is the path of original image , 
                    // the second argument is the new name of the image (I take the original name)
                    //the third argument is the width of the new image
                    // the fourth argument is the height of the new image
                    //the fifth argument is the mode of generating the new image which is mentioned above
                    resizePicture.MakeThumbnail(item, target+"/"+item.Substring(item.LastIndexOf("\\")), 300, 300, "Cut");
                    // delete the original images
                    File.Delete(item);
                }

    And the  utility class.

     public void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
            {
                System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
     
                int towidth = width;
                int toheight = height;
     
                int x = 0;
                int y = 0;
                int ow = originalImage.Width;
                int oh = originalImage.Height;
     
                switch (mode)
                {
                    case "HW":                 
                        break;
                    case "W":                    
                        toheight = originalImage.Height * width / originalImage.Width;
                        break;
                    case "H":
                        towidth = originalImage.Width * height / originalImage.Height;
                       break;
                    case "Cut":                 
                        if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                        {
                            oh = originalImage.Height;
                            ow = originalImage.Height * towidth / toheight;
                            y = 0;
                            x = (originalImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = originalImage.Width;
                            oh = originalImage.Width * height / towidth;
                            x = 0;
                            y = (originalImage.Height - oh) / 2;
                        }
                        break;
                    default:
                        break;
                }
     
            
                System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
     
          
                Graphics g = System.Drawing.Graphics.FromImage(bitmap);
     
             
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
     
             
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
     
             
                g.Clear(Color.Transparent);
     
                
                g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                 new Rectangle(x, y, ow, oh),
                 GraphicsUnit.Pixel);
     
                try
                {
                   
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                   
                }
                catch (System.Exception e)
                {
                    throw e;
                }
                finally
                {
                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }
            }
     

    Below is the result.

    Best regards,

    Ackerly Xu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 3, 2018 9:07 AM

All replies

  • User-369506445 posted

    hi

    you can use below code

     string[] filePaths = Directory.GetFiles(@"D:\images", "*.png",
                                              SearchOption.TopDirectoryOnly);
    
    
               foreach(var item in filePaths)
                {
                    WebImage img = new WebImage(item);
                    if (img.Width > 100)
                        img.Resize(100, 100);
                    img.Save(@"D:\newPath\");
                }

    the above code fetch all image from the path and then resize them and store in new path

    Wednesday, August 1, 2018 5:02 AM
  • User-257070954 posted

    Hi 

       Thanks for your answer. But i am not able to access webimage . i am working traditional asp.net application

    Wednesday, August 1, 2018 5:37 AM
  • User-369506445 posted

    please try below code

    protected void Page_Load(object sender, EventArgs e)
            {
    
                string[] filePaths = System.IO.Directory.GetFiles(@"E:\images", "*.png",
                                                System.IO.SearchOption.TopDirectoryOnly);
    
                foreach (var item in filePaths)
                {
                     ResizeImageAndSave(100, 100, item, @"E:\new\test.jpeg");
                }
    
    
            }
    
    
            public string ResizeImageAndSave(int Width, int Height, string imageUrl, string destPath)
            {
                System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(imageUrl);
                double widthRatio = (double)fullSizeImg.Width / (double)Width;
                double heightRatio = (double)fullSizeImg.Height / (double)Height;
                double ratio = Math.Max(widthRatio, heightRatio);
                int newWidth = (int)(fullSizeImg.Width / ratio);
                int newHeight = (int)(fullSizeImg.Height / ratio);
                //System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                //DateTime MyDate = DateTime.Now;
                //String MyString = MyDate.ToString("ddMMyyhhmmss") + imageUrl.Substring(imageUrl.LastIndexOf("."));
                thumbNailImg.Save(destPath  , System.Drawing.Imaging.ImageFormat.Jpeg);
                thumbNailImg.Dispose();
                return "";
            }

    Wednesday, August 1, 2018 6:04 AM
  • User-257070954 posted

    When i use your code i am getting below compile error

    Error CS0103 The name 'ThumbnailCallback' does not exist in the current context

    Wednesday, August 1, 2018 8:32 AM
  • User-369506445 posted

    I'm sorry I forgot <g class="gr_ gr_31 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del" id="31" data-gr-id="31">tp</g> put the callback method

    private bool ThumbnailCallback()
            {
                return true;
            }

    and your complete code

    protected void Page_Load(object sender, EventArgs e)
            {
    
                string[] filePaths = System.IO.Directory.GetFiles(@"E:\images", "*.png",
                                                System.IO.SearchOption.TopDirectoryOnly);
    
    
                foreach (var item in filePaths)
                {
                    ResizeImageAndSave(10, 10, item, @"E:\new\test.jpeg");
    
    
                }
    
    
            }
    
    
            public string ResizeImageAndSave(int Width, int Height, string imageUrl, string destPath)
            {
                System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(imageUrl);
                double widthRatio = (double)fullSizeImg.Width / (double)Width;
                double heightRatio = (double)fullSizeImg.Height / (double)Height;
                double ratio = Math.Max(widthRatio, heightRatio);
                int newWidth = (int)(fullSizeImg.Width / ratio);
                int newHeight = (int)(fullSizeImg.Height / ratio);
                //System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
                System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                //DateTime MyDate = DateTime.Now;
                //String MyString = MyDate.ToString("ddMMyyhhmmss") + imageUrl.Substring(imageUrl.LastIndexOf("."));
                thumbNailImg.Save(destPath  , System.Drawing.Imaging.ImageFormat.Jpeg);
                thumbNailImg.Dispose();
                return "";
            }
    
            private bool ThumbnailCallback()
            {
                return true;
            }

    Wednesday, August 1, 2018 8:39 AM
  • User-1171043462 posted

    Refer my article: Resize image on the fly and maintain (keep) Aspect Ratio in ASP.Net

    To save in folder

    protected void GenerateThumbnail(object sender, EventArgs e)
    {
        string path = Server.MapPath("~/Jellyfish.jpg");
        System.Drawing.Image image = System.Drawing.Image.FromFile(path);
        using (System.Drawing.Image thumbnail = image.GetThumbnailImage(100, 100, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                thumbnail.Save(memoryStream, ImageFormat.Png);
                Byte[] bytes = new Byte[memoryStream.Length];
                memoryStream.Position = 0;
                memoryStream.Read(bytes, 0, (int)bytes.Length);
                string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
                Image2.ImageUrl = "data:image/png;base64," + base64String;
                Image2.Visible = true;
                 //Save to Folder
                File.WriteAllBytes(Server.MapPath("~/Jellyfish_small.jpg"), bytes);
            }
        }
    }
     
    public bool ThumbnailCallback()
    {
        return false;
    }
    

    Wednesday, August 1, 2018 8:57 AM
  • User-893317190 posted

    Hi binustrat ,

    I suggest you could use a utility class to  help you resize your image  more easily.

    I have created an example:
    This class contains four modes which could resize the image by height or width.

     The first mode named “HW”  is to  resize the image according the width and height specified ,which may cause distortion

     

    The second mode named “H” is to resize the image according to the height.

     

    The third mode named “W” is to resize the image according to the width .

     

    The fourth mode  named “Cut” is to resize the image according to the width and height specified which doesn’t  cause distortion.

     

     
    Below is my code.

    // get the absolute path of the original folder
                string path = Server.MapPath("~/Format/imageTest");
                // get all the absolute pathes  of files in the original folder
               string[] images= Directory.GetFiles(path);
                //get the absolute path of the targeted folder
               string target= Server.MapPath("~/Format/imageTarget");
                //initialize the util class
                ResizePicture resizePicture = new ResizePicture();
                //loop through the  pathes
               foreach (var item in images)
                {
                  
                
                    // the first argument is the path of original image , 
                    // the second argument is the new name of the image (I take the original name)
                    //the third argument is the width of the new image
                    // the fourth argument is the height of the new image
                    //the fifth argument is the mode of generating the new image which is mentioned above
                    resizePicture.MakeThumbnail(item, target+"/"+item.Substring(item.LastIndexOf("\\")), 300, 300, "Cut");
                    // delete the original images
                    File.Delete(item);
                }

    And the  utility class.

     public void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
            {
                System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);
     
                int towidth = width;
                int toheight = height;
     
                int x = 0;
                int y = 0;
                int ow = originalImage.Width;
                int oh = originalImage.Height;
     
                switch (mode)
                {
                    case "HW":                 
                        break;
                    case "W":                    
                        toheight = originalImage.Height * width / originalImage.Width;
                        break;
                    case "H":
                        towidth = originalImage.Width * height / originalImage.Height;
                       break;
                    case "Cut":                 
                        if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                        {
                            oh = originalImage.Height;
                            ow = originalImage.Height * towidth / toheight;
                            y = 0;
                            x = (originalImage.Width - ow) / 2;
                        }
                        else
                        {
                            ow = originalImage.Width;
                            oh = originalImage.Width * height / towidth;
                            x = 0;
                            y = (originalImage.Height - oh) / 2;
                        }
                        break;
                    default:
                        break;
                }
     
            
                System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
     
          
                Graphics g = System.Drawing.Graphics.FromImage(bitmap);
     
             
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
     
             
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
     
             
                g.Clear(Color.Transparent);
     
                
                g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                 new Rectangle(x, y, ow, oh),
                 GraphicsUnit.Pixel);
     
                try
                {
                   
                    bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                   
                }
                catch (System.Exception e)
                {
                    throw e;
                }
                finally
                {
                    originalImage.Dispose();
                    bitmap.Dispose();
                    g.Dispose();
                }
            }
     

    Below is the result.

    Best regards,

    Ackerly Xu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 3, 2018 9:07 AM