Solved

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

Posted on 2011-03-20
12
805 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

777 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