.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

System.Drawing.Image.FromStream() get a Parameter is not valid

Posted By:      Posted Date: May 22, 2011    Points: 0   Category :Windows Application

Anyone help fix Parameter is not valid errors , when i tried rename and save a file using fileupload to server

my code here :

if (fupImage.PostedFile.FileName != "")
                if (!Utitlties.Instance.CheckImageFileType(fupImage.PostedFile.FileName))
                    lblMessageForfupImage.Visible = true;
                    lblMessageForfupImage.Text = "Image file only accept *.jpg, *.png, *.bmp, *.gif Extensions !";
                    evt.ImageURL = Utils.Instance.SaveImage(fupImage.PostedFile.InputStream, fupImage.PostedFile.FileName, true);

anh here is methos SaveImage :


public string SaveImage(Stream stream, string filename, bool IsImageFile/*, bool CreateThumImage*/)
        string ImgUrl = string.Empty;
        string d = Utitlties.Instance.MakeFolderName();
        System.Drawing.Image img;
        string dirToSave = HttpContext.Current.Server.MapPath("Images/Uploads") + "/" + d + "/";
        string dir = "Images/Uploads/" + d + "/";
            if (IsImageFile == true)

View Complete Post

More Related Resource Links

System.Drawing.Image.FromStream() ArgumentException: Parameter not valid.


I am getting an ArgumentException: Parameter is not valid.

Does anyone know what's wrong with my code here?

        ImgService obj = new ImgService();

        byte[] data = obj.ShowImg(6);

        Int32 offset = 78;

        MemoryStream memStream = new MemoryStream();

        memStream.Write(data, offset, data.Length - offset);

        System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);

        img.Save(Server.MapPath("image.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);


        Image1.ImageUrl = Server.MapPath("image.jpg");


        ImgService obj = new ImgService();

        byte[] data = obj.ShowImg(6);
        Int32 offset = 78;

Parameter is not valid exception on image.fromstream() method



      i have written a code for resizing the images and its working good except for some images that too the issue is occuring only on locolhost(IIS). I have asynchronous file upload contorl and two button  controls. when clicked on first button  the asynchronous file upload control is saved in session using the following code

Session["myupload"] = AsyncFileUpload1.PostedFile;

The image is resized and saved in a folder when second button clicked. The following code will execute when clicked the second button.

HttpPostedFile hif = (HttpPostedFile)Session["myupload"]                        
                        if (hif.ContentLength <= 20000000)
                            if (checkfiletype(hif.FileName))
                                string spacefileName = hif.FileName;                                
                                string storePath = Server.MapPath("~") + "/Docs";
                                //MemoryStream source = hif.InputStream;
                                Stream source = hif.InputStream;
                                //source =(MemoryStream)hif.InputStream;
                                byte[] input=new byte[hif.ContentLength

System.Drawing.Image.Fromfile is not working


I am trying to get the height and width of the image dynamically.  The reason is I am loading multiple images using code, where the image name is from the database. 

Here is my code:

in the ascx page, I have an asp image

<asp:image id="imgInfo" runat="server" /> 


In the code behind

string ImagePath = "~/products/img/" + dataviewImgInfo[0]["imgName"].ToString();

System.Drawing Image imgProd = System.Drawing.Image.FromFile(ImagePath);

if(imgProd.Height > 200)

imgInfo.Height = 100;




imgInfo.Height = 200



WHen I run this page I am getting the folloiwng error

Displaying a System.Drawing.Bitmap in a WPF Image control

How would I convert a System.Drawing.Btimap into a comparable WPF image control so I can display in on my WPF window? Thanks

SSRS 2008 Export to PDF fails for large data with System.Exception: Parameter is not valid

Hi, We are working on Range Bar Chart using SSRS 2008. The report has huge data. It is properly displaying the data, but when we tried to export to pdf it is failing with the following exception. Exporting to excel works fine. Also if the report has small/medium data it is property exporting to PDF. It is failing only in case of huge data (we have custom page size of 28" X 14"). Of course the report has lot of expressions we used to customize the colors/text as per our requirements.   Server Error in '/Reports_SQLDEV2008' Application. Parameter is not valid. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Exception: Parameter is not valid. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace:   [Exception: Parameter is not valid.]   [Exception: An error occurred during rendering of the report.]   [Exception: An error occurred during rendering of the report.]    Microsoft.Reporting.WebForms.ServerReport.ServerUrlRequest(Boolean isAbortable, String url, Stream ou

Winnovative:Could not save image. Parameter is not valid.

while running website,the image get extracted from pdf document but still an exception named pdfimgextractexception appears at the end of an application.please give me the solution regarding this problem. code as follows: pdfImgExtractor.ExtractImages(srcPdfFile,true); which calls an eventhandler: pdfImgExtractor.ImageExtractedEvent += new ImageExtractedEventHandler(pcmd.pdfImgExtractor_ImageExtractedEvent); where the definition is: {   try { System.Drawing.     ographics = ographics.DrawImage(extractedBitmap, extractedBitmap.Dispose(); extractedBitmap = obitmap;     ographics.DrawString( ographics.Dispose(); ofont.Dispose(); oBrush.Dispose(); extractedBitmap.Save( extractedBitmap.Dispose(); }   {   }   Bitmap extractedBitmap = args.ExtractedBitmap;Graphics ographics;Bitmap obitmap = new Bitmap(extractedBitmap.Width, extractedBitmap.Height);Graphics.FromImage(obitmap);new Rectangle(0, 0, obitmap.Width, obitmap.Height), 0, 0, extractedBitmap.Width, extractedBitmap.Height, GraphicsUnit.Pixel);SolidBrush oBrush = new SolidBrush(Color.Black);Font ofont = new Font("Arial", 8);"Some text to write", ofont, oBrush, 10, 10);"D:\\example.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);catch (Exception err)HttpContext.Current.Response.Write(err.Message); } thanks in advance.

System.Drawing.Image.FromFile crashes for tiff files on 64bit system


The following pice of code runs fine on my development machine (win7, 32bit) but ends with Exception on the server (Win2008R2, 64bit).


        static void Main(string[] args)


            Image image = Image.FromFile(args[0]);





The exception will be thrown for TIFF files (from other sources) but ie not for PNG files.

I was wondering why the test program above works fine on my Win 32bit machine with .NET 4 but not on my 64bit machine with .NET 4.

Any help appreciated.



How to Convert System.Drawing.Image Variable to Byte variable



I got a variable of type System.Drawing.Image and need to convert it to a variable of type byte so I can store the image in the database. Can someone show me how to do that in VB.NET code.

Thanks alot

Get Image from HTTP in a System.Drawing.Image


How can i get a Image that exitsts on the WWW, into my project.
Normally i get a image on this way:


        System.Drawing.Image ImgWatermerk = System.Drawing.Image.FromFile(PNGPath);


But right now the image is remote like http://www.google.nl/google.jpg


"Parameter is not valid" for tif image(JPEG cpmpressed)


I am agetting the "Parameter is not valid" message while converting the tif image (jpeg compressed) to the Bitmap

FileStream stream =new FileStream(strFilePath, FileMode.Open, FileAccess.Read); 
Bitmap bmp = (Bitmap)Bitmap.FromStream(stream); //here the exception occurs... 



Hi there,


 I am doing one task on asp.net graphics. i would like to a form that let the user choose the color code from the color picker.

inside my backend code, i can get the color code and convert to the system.drawing.color.



Dim col As System.Drawing.Color = System.Drawing.ColorTranslator.FromHtml("#9932CC")

 Dim Brush As New SolidBrush(col)


but i have some problem in make this col object to alpha color. as i know the .net code that make the system color to become alpha is wrote as like tat :

gr.DrawString(strWatermarkText, wmFont, New SolidBrush(Color.FromArgb(8, 0, 0, 0)), x, y)


May someone share me how to make the color input from form to become alpha color? thanx in advanced. hope to hear from you all soon 


EventType clr20r3, P1 devenv.exe, P2 9.0.30729.1, P3 488f2b50, P4 system.drawing, P5, P6 488

Hi,I am facing a strange issue in Visual Studio 2008 Standard SP1, when using WPF Designer (even without using the Designer tab, only XAML tab). Visual Studio crashes very often, without any apparent reason, and in various ways, for example: exits instantly, the IDE displays corrupted UI, when begining compiling it stops responding.There are two new Event Log entries after this: EventType clr20r3, P1 devenv.exe, P2 9.0.30729.1, P3 488f2b50, P4 system.drawing, P5, P6 4889dec2, P7 33d, P8 18, P9 system.outofmemoryexception, P10 NIL. .NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A2E0F92) (0)Worth mentioning:- computer has Windows XP SP3 with the latest updates installed- it crashes on other computer types too- the project has quite a large number of UserControls - it appears that if opening a XAML file with the XML editor instead, it works ok- on other WPF projects it also works okDoes anyone have an ideea why is this happening and solutions? Thanks

System.InvalidOperationException: Instance operation is not valid on workflow runtime thread

Am getting the exception related in the title of this article when using the StateMachineWorkflowInstance object to arbitarily set state in my workflow code; and am unsure why.  The code follows below:   500     Protected Overrides Function Execute(ByVal executionContext As System.Workflow.ComponentModel.ActivityExecutionContext) As System.Workflow.ComponentModel.ActivityExecutionStatus   501    502    506         Dim smwi As StateMachineWorkflowInstance = New StateMachineWorkflowInstance(StaticWFRuntime.LocalRuntime, Me.WorkflowInstanceId)   511    512         'set workflow-wide database connection string   513         _connectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString   518    519         Utility.LogEnabled()   520    521         Utility.FoaeaLogger.WriteEntry("Processing TracingApplication.Execute()....", EventLogEntryType.Information)   522         If StaticWFRuntime.LocalRuntime Is Nothing OrElse StaticWFRuntime.LocalRuntime.IsStarted = False Then   523             Utility.FoaeaLogger.WriteEntry("No static RuntimeService object exists!", EventLogEntryType.Warning)   524         End If   525    526         Return MyBase.Execute(executionContext)   527    528     End Function   796     Private Sub gotoState2_ExecuteCode(ByVal sender As System.Object, ByVal e As System.EventArgs)   797    798        

Databind on Gridview throwing System.InvalidCastException. Specific Cast Not Valid

Hello, I am working on a web app where when the user enters data into a text box and presses a filter radio button it should filter the Gridview on the page to the criteria entered.  I have done this before in previous applications with the same code listed below, but for some reason I am now getting the InvalidCastExeption error.  Any help would be appreciated, the source database is SQL and the data field is set to nvarchar and I am using a string to compare as you will see in the code.  I am just unsure why this worked in the past and is not working in this scenario. Thanks, Pete protected void filterLName_CheckedChanged(object sender, EventArgs e) { SHCDataContext existingCustomers = new SHCDataContext(); var filterExistingCustomers = existingCustomers.Customers.Where(c => c.custLastName.Contains(lNameTB.Text.ToString())); displayCustGV.DataSource = null; displayCustGV.DataSourceID = null; displayCustGV.DataSource = filterExistingCustomers; displayCustGV.DataBind(); }   Here is the stack trace....  Specified cast is not valid. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.I

Converting System.Windows.Media to System.Drawing objects

Hello, I want to know if it's possible to convert the System.Windows.Media objects Color and Imaging.BitmapSource to the System.Drawing objects Color and Bitmap and the other way around. If yes, how can I do this?

ImageList and a system image list handle

How can I have an ImageList use an image list handle of a systems image list, such as one that can be returned from SHGetFileInfo ? My image list is associated with a ListView control and this could be easily done in Win32 through the LVM_SETIMAGELIST message with an image list handle but I see no easy way of doing this with the .Net System.Windows.Forms.ImageList component.

XmlSerializer: Serialize an array of System.Drawing.Color

Ok,  here is my problem... I am building a UI configuration tool that utiliizes a PropertyGrid.  One of the properties is a indexed list of Colors contained in an array: CategoryAttribute("Style"), DisplayName("Data Set Colors"), DescriptionAttribute(""), XmlArray("SetColors"), XmlArrayItem(ElementName="Color",Type=typeof(SColor))] public Color[] SetColors { get; set; } The beauty of the PropertyGrid is it knows how to handle this Poperty and properly handles array and list of Colors. BUT...   As we already know in order to serialize a Color,  we have to use a surrigate property,  which is very unfortunate, and I fear is one of those little thing MS just overlooked.  (I understand it is actually a structure and not a class and has not default properties from which to get type info from.) I am really amazed that when I do serialize the class,  the XML is soooo  close to what I need,  its just missing the actual color value data: <AppGridColumnConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Name>Label</Name> <SetColors> <Color /> <Color /> <Color /> </SetColors> <IsDefaultEditable>false</IsDefaultEditable> <IsDirtyCheck&
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend