Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2011-03-20
12
Medium Priority
?
820 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 6
12 Comments
 
LVL 14

Assisted Solution

by:systan
systan earned 2000 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
Linux Academy Android App Now Supports Chromecast

We have some fantastic news for our Android fans. We’re so excited to announce that the Linux Academy Android app is now available with Chromecast support. That’s right – simply download the latest update of the Linux Academy App and start casting your favorite course videos!

 
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

719 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