Solved

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

Posted on 2011-03-20
12
815 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 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
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

617 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