Solved

Image.FromFile("1.jpg") 'Parameter is not Valid'

Posted on 2011-03-20
12
800 Views
Last Modified: 2012-08-14
I'm uing the code below to resize an Image. This works well when the JPG has a name other than a simple number. If I try to use 1.jpg, 2.jpg etc.. I get an error 'Parameter is not Valid'.

Anyone know why this is, does the filename need to be in a certain format? Can anyone suggest another method of loading the file.

Thanks
private void ReSize(string OriginalFile, string NewFile, int Width, int Height)
        {

            Bitmap imgOutput=null;
            Image imgOriginal=null;
            try
            {

                const int intMaxWidth = 1920;
                //max width 
                const int intMaxHgt = 1080;
                //max height 
                int intNewWidth = 0;
                int intNewHgt = 0;
                // new width/height 
                float sglSize = 0;
                //temp variable used when calculating new size 
                imgOriginal = default(Image);
                //holds the original image 
                imgOriginal = Image.FromFile(OriginalFile);

                if ((imgOriginal.Width / intMaxWidth) > (imgOriginal.Height / intMaxHgt))
                {
                    sglSize = imgOriginal.Width;
                    intNewWidth = intMaxWidth;
                    intNewHgt = imgOriginal.Height * (intMaxWidth / (int)sglSize);
                    if (intNewHgt > intMaxHgt)
                    {
                        intNewWidth = intNewWidth * (intMaxHgt / intNewHgt);
                        intNewHgt = intMaxHgt;
                    }
                }
                else
                {
                    sglSize = imgOriginal.Height;
                    intNewHgt = intMaxHgt;
                    intNewWidth = imgOriginal.Width * (intMaxHgt / (int)sglSize);
                    if (intNewWidth > intMaxWidth)
                    {
                        intNewHgt = intNewHgt * (intMaxWidth / intNewWidth);
                        intNewWidth = intMaxWidth;
                    }
                }

                //Create a graphics object    
                imgOutput = new Bitmap(intNewWidth, intNewHgt);
                imgOutput = (Bitmap)imgOriginal.GetThumbnailImage(intNewWidth, intNewHgt, null, IntPtr.Zero);

                Graphics gr_dest = Graphics.FromImage(imgOutput);
                //Re-draw the image to the specified height and width 
                gr_dest.DrawImage(imgOriginal, 0, 0, imgOutput.Width, imgOutput.Height);
                //imgOriginal.Dispose();
                imgOutput.Save(NewFile, imgOriginal.RawFormat);

                //Dispose of Files
                imgOutput.Dispose();
                imgOriginal.Dispose();
            }
            catch (Exception ex)
            {
                string msg = "Resize Image after Upload Error: ";
                msg += ex.Message;
                emailData(msg, "ENERGYweb Error");
                string timestamp = DateTime.Now.ToString();
                new Logger.Logger().ErrorLog(timestamp + msg);

            }
            finally
            {
                //Make sure things have been cleaned up
                if (imgOriginal != null)
                {
                    imgOriginal.Dispose();
                    imgOriginal = null;
                }
                if (imgOutput != null)
                {
                    imgOutput.Dispose();
                    imgOutput = null;
                }
            }


        }

Open in new window

0
Comment
Question by:wint100
  • 6
  • 6
12 Comments
 
LVL 14

Assisted Solution

by:systan
systan earned 500 total points
ID: 35174633
private void SavePhotoAndResize(string filepath, int wid, int hig)
{
      FileStream stream1 = null;
      Image imgTmp = null;
      stream1 = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
      imgTmp = Image.FromStream(stream1, false, false);
      System.Drawing.Bitmap imgFoto = null;
      imgFoto = new System.Drawing.Bitmap(wid, hig);
      Rectangle recDest = new Rectangle(0, 0, wid, hig);
      Graphics gphCrop = Graphics.FromImage(imgFoto);
      gphCrop.SmoothingMode = SmoothingMode.HighQuality;
      gphCrop.CompositingQuality = CompositingQuality.HighQuality;
      gphCrop.InterpolationMode = InterpolationMode.High;
      gphCrop.DrawImage(imgTmp, recDest, 0, 0, imgTmp.Width, imgTmp.Height, GraphicsUnit.Pixel);
      System.Drawing.Imaging.Encoder myEncoder = null;
      System.Drawing.Imaging.EncoderParameter myEncoderParameter = null;
      System.Drawing.Imaging.EncoderParameters myEncoderParameters = null;
      System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
      System.Drawing.Imaging.ImageCodecInfo jpegICI = null;
      int x = 0;
      for (x = 0; x <= arrayICI.Length - 1; x++) {
            if ((arrayICI(x).FormatDescription.Equals("JPEG"))) {
                  jpegICI = arrayICI(x);
                  break;
            }
      }
      myEncoder = System.Drawing.Imaging.Encoder.Quality;
      myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
      myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 60L);
      myEncoderParameters.Param(0) = myEncoderParameter;
      imgFoto.Save(filepath, jpegICI, myEncoderParameters);
      imgFoto.Dispose();
      imgTmp.Dispose();
}
0
 
LVL 1

Author Comment

by:wint100
ID: 35174673
Thanks. How would this work with PNG or BMP files, as the files could be of any image file type.
0
 
LVL 1

Author Comment

by:wint100
ID: 35174685
Also, it seesm that this code doesn't preserve the aspect ratio of the image, it will always results in a stretched image.
0
 
LVL 14

Expert Comment

by:systan
ID: 35174703
Just change something in the code;
...
using System.Drawing.Imaging;
using System.Drawing.Drawing2D ;
...
...
private void SavePhotoAndResize(string filepath_SOurce, string filepath_DEstination, int wid, int hig)
{
FileStream stream1 = null;
Image imgTmp = null;
stream1 = new FileStream(filepath_SOurce, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
...
...
imgFoto.Save(filepath_DEstination, jpegICI, myEncoderParameters);
imgFoto.Dispose();
imgTmp.Dispose();
}
0
 
LVL 1

Author Comment

by:wint100
ID: 35174729
Ok, but I'm still not having the apsect ratio preserved, the image gets distorted as the width and height are forced to the set params. If you look in the old code, the aspect ratio gets preserved, as the params are only the max allowed width/height, rather than the actual width/height.
0
 
LVL 14

Expert Comment

by:systan
ID: 35174755
>>How would this work with PNG or BMP files, as the files could be of any image file type.
yes

>>the old code, the aspect ratio gets preserved,
oh, merge your code with the aspect ratio preserved.
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 14

Expert Comment

by:systan
ID: 35174776
>> 'Parameter is not Valid' ?
try putting @ before the file
Image.FromFile(@"1.jpg")

or put exactly the real path
Image.FromFile("c:\\1.jpg")
0
 
LVL 1

Author Comment

by:wint100
ID: 35174817
Ok, it seemed the problem was with the aspect ratio preservation part of the code. Because the IntNewWidth was involved in a calculation invloving integers, it was always returning '0', so the error was thrown by the BitMap creation, as it was trying to create a BitMap with a width of 0. Here is the new code.

How does your code improve on what I already had, is there a benefit in using the code you provided, instead of my original code?

private void SavePhotoAndResize(string filepath_SOurce, string filepath_DEstination, int intMaxWidth, int intMaxHgt)

        {
            FileStream stream1 = null;
            Image imgTmp = null;
            stream1 = new FileStream(filepath_SOurce, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            imgTmp = Image.FromStream(stream1, false, false);
            System.Drawing.Bitmap imgFoto = null;

            int intNewWidth = 0;
            int intNewHgt = 0;
            // new width/height 
            float sglSize = 0;
            

            if ((imgTmp.Width / intMaxWidth) > (imgTmp.Height / intMaxHgt))
            {
                sglSize = imgTmp.Width;
                intNewWidth = intMaxWidth;
                intNewHgt = imgTmp.Height * (intMaxWidth / (int)sglSize);
                if (intNewHgt > intMaxHgt)
                {
                    intNewWidth = intNewWidth * (intMaxHgt / intNewHgt);
                    intNewHgt = intMaxHgt;
                }
            }
            else
            {
                
                sglSize = imgTmp.Height;
                intNewHgt = intMaxHgt;
                intNewWidth = (int)((decimal)imgTmp.Width * ((decimal)intMaxHgt / (decimal)sglSize));
                if (intNewWidth > intMaxWidth)
                {
                    intNewHgt = intNewHgt * (intMaxWidth / intNewWidth);
                    intNewWidth = intMaxWidth;
                }
            }


            imgFoto = new System.Drawing.Bitmap(intNewWidth, intNewHgt);
            Rectangle recDest = new Rectangle(0, 0, intNewWidth, intNewHgt);
            Graphics gphCrop = Graphics.FromImage(imgFoto);
            gphCrop.SmoothingMode = SmoothingMode.HighQuality;
            gphCrop.CompositingQuality = CompositingQuality.HighQuality;
            gphCrop.InterpolationMode = InterpolationMode.High;
            gphCrop.DrawImage(imgTmp, recDest, 0, 0, imgTmp.Width, imgTmp.Height, GraphicsUnit.Pixel);
            System.Drawing.Imaging.Encoder myEncoder = null;
            System.Drawing.Imaging.EncoderParameter myEncoderParameter = null;
            System.Drawing.Imaging.EncoderParameters myEncoderParameters = null;
            System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            System.Drawing.Imaging.ImageCodecInfo jpegICI = null;
            int x = 0;
            for (x = 0; x <= arrayICI.Length - 1; x++)
            {
                if ((arrayICI[x].FormatDescription.Equals("JPEG")))
                {
                    jpegICI = arrayICI[x];
                    break;
                }
            }
            myEncoder = System.Drawing.Imaging.Encoder.Quality;
            myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 60L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            imgFoto.Save(filepath_DEstination, jpegICI, myEncoderParameters);
            
            imgFoto.Dispose();
            imgTmp.Dispose();
            stream1.Close();
            stream1.Dispose();
        }

Open in new window

0
 
LVL 14

Expert Comment

by:systan
ID: 35174831
Great;
Actually I don't know the real benifit, I way I see are both fine, converts any image to jpg, resize any image to wanted size.
0
 
LVL 14

Expert Comment

by:systan
ID: 35176030
>>Because the IntNewWidth was involved in a calculation invloving integers, it was always returning '0'

Ok, then removed it to work fine.
if (intNewHgt > intMaxHgt)
                {
                    ////intNewWidth = intNewWidth * (intMaxHgt / intNewHgt); //removed
                    intNewHgt = intMaxHgt;
                }
            }
            else
            {
               
                sglSize = imgTmp.Height;
                intNewHgt = intMaxHgt;
                intNewWidth = (int)((decimal)imgTmp.Width * ((decimal)intMaxHgt / (decimal)sglSize));
                if (intNewWidth > intMaxWidth)
                {
                    ////intNewHgt = intNewHgt * (intMaxWidth / intNewWidth); //removed
                    intNewWidth = intMaxWidth;
                }
0
 
LVL 1

Accepted Solution

by:
wint100 earned 0 total points
ID: 35176779
This is the final code that works very well:
private void SavePhotoAndResize(string filepath_SOurce, string filepath_DEstination, int intMaxWidth, int intMaxHgt)

        {
            FileStream stream1 = null;
            Image imgTmp = null;
            stream1 = new FileStream(filepath_SOurce, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            imgTmp = Image.FromStream(stream1, false, false);
            System.Drawing.Bitmap imgFoto = null;

            int intNewWidth = 0;
            int intNewHgt = 0;
            // new width/height 
            float sglSize = 0;
            

            if ((imgTmp.Width / intMaxWidth) > (imgTmp.Height / intMaxHgt))
            {
                sglSize = imgTmp.Width;
                intNewWidth = intMaxWidth;
                intNewHgt = (int)((decimal)imgTmp.Height * (decimal)(intMaxWidth / (decimal)sglSize));
                if (intNewHgt > intMaxHgt)
                {
                    intNewWidth = (int)((decimal)intNewWidth * ((decimal)intMaxHgt / (decimal)intNewHgt));
                    intNewHgt = intMaxHgt;
                }
            }
            else
            {
                
                sglSize = imgTmp.Height;
                intNewHgt = intMaxHgt;
                intNewWidth = (int)((decimal)imgTmp.Width * ((decimal)intMaxHgt / (decimal)sglSize));
                if (intNewWidth > intMaxWidth)
                {
                    intNewHgt = (int)((decimal)intNewHgt * (decimal)(intMaxWidth / (decimal)intNewWidth));
                    intNewWidth = intMaxWidth;
                }
            }


            imgFoto = new System.Drawing.Bitmap(intNewWidth, intNewHgt);
            Rectangle recDest = new Rectangle(0, 0, intNewWidth, intNewHgt);
            Graphics gphCrop = Graphics.FromImage(imgFoto);
            gphCrop.SmoothingMode = SmoothingMode.HighQuality;
            gphCrop.CompositingQuality = CompositingQuality.HighQuality;
            gphCrop.InterpolationMode = InterpolationMode.High;
            gphCrop.DrawImage(imgTmp, recDest, 0, 0, imgTmp.Width, imgTmp.Height, GraphicsUnit.Pixel);
            System.Drawing.Imaging.Encoder myEncoder = null;
            System.Drawing.Imaging.EncoderParameter myEncoderParameter = null;
            System.Drawing.Imaging.EncoderParameters myEncoderParameters = null;
            System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            System.Drawing.Imaging.ImageCodecInfo jpegICI = null;
            int x = 0;
            for (x = 0; x <= arrayICI.Length - 1; x++)
            {
                if ((arrayICI[x].FormatDescription.Equals("JPEG")))
                {
                    jpegICI = arrayICI[x];
                    break;
                }
            }
            myEncoder = System.Drawing.Imaging.Encoder.Quality;
            myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
            myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 60L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            imgFoto.Save(filepath_DEstination, jpegICI, myEncoderParameters);
            
            imgFoto.Dispose();
            imgTmp.Dispose();
            stream1.Close();
            stream1.Dispose();
        }

Open in new window

0
 
LVL 1

Author Closing Comment

by:wint100
ID: 35213320
Problem solved
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now