Link to home
Start Free TrialLog in
Avatar of wint100
wint100Flag for United Kingdom of Great Britain and Northern Ireland

asked on

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

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

SOLUTION
Avatar of systan
systan
Flag of Philippines image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of wint100

ASKER

Thanks. How would this work with PNG or BMP files, as the files could be of any image file type.
Avatar of wint100

ASKER

Also, it seesm that this code doesn't preserve the aspect ratio of the image, it will always results in a stretched image.
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();
}
Avatar of wint100

ASKER

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.
>>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.
>> 'Parameter is not Valid' ?
try putting @ before the file
Image.FromFile(@"1.jpg")

or put exactly the real path
Image.FromFile("c:\\1.jpg")
Avatar of wint100

ASKER

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

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.
>>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;
                }
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of wint100

ASKER

Problem solved