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

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

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

Posted By:      Posted Date: April 10, 2011    Points: 0   Category :Windows Application


      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

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;

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


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)

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.

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

TimeOut exception when using MetadataExchangeClient GetMetadata method with valid mex EndpointAddres


Hello all,

I have a ServiceHost with a defined tcp mex endpoint at net.tcp://localhost:9003/MyService/mex. Other code can successfully read metadata from the endpoint.

Using the following code, I get a TimeOut exception with this error message even though the timeout interval is set to 3 minutes:

This request operation sent to net.tcp://localhost:9003/CalculatorService/mex did not receive a reply within the configured timeout (00:03:00).  The time allotted to this operation may have been a portion of a longer timeout.  This may be because the service is still processing the operation or because the service was unable to send a reply message.  Please consider increasing the operation timeout (by casting the channel/proxy to IContextChannel and setting the OperationTimeout property) and ensure that the service is able to connect to the client.

MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress);

// mexClient.HttpCredentials = New System.Net.NetworkCredential()

mexClient.ResolveMetadataReferences = true;

mexClient.OperationTimeout = New TimeSpan(0, 3, 0);

MetadataSet metaDocs = mexClient.GetMetadata();

The metadataAddress comes f

Cash Drawer - Method Open threw an exception - Windows Service

Hi All, I'm getting the following exception while calling Open method of Cash Drawer object. Method Open threw an exception.  Could not read the device name key's default value, or could not convert the Programmatic ID it holds into a valid Class ID. Code:   class Class1 { CashDrawer _uniCashDrawer1 = null; DeviceInfo cashDrawerDevice1 = null; PosExplorer posExplorer = new Microsoft.PointOfService.PosExplorer();   public void ClaimCashDrawer() { cashDrawerDevice1 = posExplorer.GetDevice("CashDrawer", "testDrawer"); if (cashDrawerDevice1 != null) { _uniCashDrawer1 = posExplorer.CreateInstance(cashDrawerDevice1) as CashDrawer; if (_uniCashDrawer1 != null) { _uniCashDrawer1.StatusUpdateEvent += new StatusUpdateEventHandler(UniCashDrawer1_StatusUpdateEvent); _uniCashDrawer1.Open(); _uniCashDrawer1.Claim(0); _uniCashDrawer1.DeviceEnabled = true; } } } }   Tha above code works fine if you put the code in WindowsApplication in all POS systems. The same is working if you put the code in Windows Service in all other POS systems. The same is not working if you put the code in Windows Service in Aures Galeo POS systems.  Thanks in advance. Ramakrishnan S

[Odd]Specified cast is not valid exception

protected float getUserBalance() { string AccountNo = Session["AccNo"].ToString(); myConnection.Open(); float balance = 0; try { OleDbCommand getBalance = new OleDbCommand("Select Balance from BankTransaction where AccountNo = '" + Session["AccNo"] + "'", myConnection); //OleDbDataReader rdrBalance = getBalance.ExecuteReader(); //while (rdrBalance.Read()) //{ // balance = rdrBalance.GetFloat(0); //} balance = float.Parse(getBalance.ExecuteScalar().ToString()); } catch { balance = 0; } myConnection.Close(); return balance; } ===============These are my codes, and it work fine, balance will has a right value, but if I comment the line "balance = float.Parse(getBalance.ExecuteScalar().ToString());"and decomment the 5 lines above, get rid of try catch, I get the error:"Specified cast is not valid"Here is the some informations when I addwatch rdrBalance-        rdrBalance    {System.Data.OleDb.OleDbDataReader}    System.Data.OleDb.OleDbDataReader+        base    {System.Dat

Calling a method with a class object as parameter data type.

   [WebMethod]    public string GetInfo(Customer inCust)    {        // Code in here    } I have a web service that resides on a remote server. I want to call a public method of theweb service named  "GetInfo". The method is shown above. The web service method expects a class object oftype "Customer". What I did to create a Customer object was to define in my asp.net project my own class named "Customer" which is exactlythe same as the class that belongs to the web service project on the remote server. I then created an instance of Customerand tried to call the web service passing in an object of type customer : my.Service ws = new my.Service(); // Get web service connectionCustomer aCustomer = new Customer();aCustomer.Initialize();ws.GetInfo(aCustomer) // call web service passing in a Customer object The problem is that the compiler gives me the following error: Value of type '_Default.Customer' cannot be converted to 'ws.Class1'. Here Default is refering to my Default.aspx.cs code. Why is this? Do I need to Cast my "aCustomer" class object to a type ofws.Customer ? How do I do that?

Why request parameter added to client side code in each method while using svcutil.exe

Hi, I am using WCF services in my project and want to call WCF methods asynchronously. I am hosting WCF service programmatically in windows app as follows svc = New ServiceHost(GetType(Service1), New Uri("net.tcp://localhost:8806/")) Dim svcMDB As New ServiceMetadataBehavior svc.Description.Behaviors.Add(svcMDB) svc.AddServiceEndpoint(GetType(Service1), New NetTcpBinding(), "MyBusiness/MyBusinessService/") svc.AddServiceEndpoint(ServiceMetadataBehavior.MexContractName, MetadataExchangeBindings.CreateMexTcpBinding(), "MyBusiness/MyBusinessService/mex") svc.Open() Me.Text = "Service started...." and I am generating client side proxy using svcutil.exe as follows. svcutil /n:net.tcp://localhost:8806/MyBusiness/MyBusinessService,MyService net.tcp://localhost:8806/MyBusiness/MyBusinessService/mex /a /language:vb   The result of this command is as :   Microsoft (R) Service Model Metadata Tool [Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.2152] Copyright (c) Microsoft Corporation.  All rights reserved.   Attempting to download metadata from 'net.tcp://localhost:8806/MyBusiness/MyBusi nessService/mex' using WS-Metadata Exchange. This URL does not support DISCO. Generating files... D:\Prabodh\New C2k\Test Projects\DataTableToArray\MyHost\bin\Debug\MyBusinessSer vice.vb D:

Parameter names ending with "specified" added to web service method call

Hello,I am new to WCF. I created a wcf web service and the generated web method exposed by wcf has some additional boolean parameters with names that end with "Specified".I am trying to understand why are these additional parameters necessary and how to get rid of them. Thanks!David

Weird Exception: Method not found: 'Double System.Windows.Controls.ScrollViewer.get_ContentHorizon

Hi guys I have an XBAP application that uses a Xamdatagrid from Infragistics. I have some filtering on this grid, that rebinds after a filter. The problem is, when a user has scrolled to a certain point and then filters, the rebinding causes the grid to scroll to the beginning position of the grid. Now how I solve this is by getting an instance of the ScrollViewer, I get the ScrollViewer.ContentHorizontalOffset and then I do a ScrollViewer.ScrollToHorizontalOffset after it filters.   Now here comes the problem. For 99% of the users of this xbap app, this will work absolutely fine. Most, if not all of the users run exactly the same machines, XP 64 bit with 8GB RAM. The other 1% get the error: Method not found: 'Double System.Windows.Controls.ScrollViewer.get_ContentHorizontalOffset()'. I cannot reproduce this error on my own box, our dev server or our production server, it is a phantom exception that only pops up on a certain condition. I have even wrapped the "offending" code in a try catch and it still doesn't solve it. If I set the DispatcherUnhandledExceptionArgs Handled to true, it works, but it doesn't feel right. How is this possible? If the method doesn't exist, how can it compile? Why does that method exist for 99% of the other users running the exact same machines? I have googled my fingers raw without any valid results and this issue is frustrat

Input Parameter in Finder Method BDC Model

Hi Guys, I know it is possible to create a Finder method with an input parameter, but I am trying to figure out how to pass the parameter to the method. Here's my isssue:   I have created a BDC Model in VS2010, my finder needs to have an input parameter. This input parameter is available on a list that is already available on my site. What are my options to pass this parameter to my finder method and display the results?   My intention (not sure if it makes sense) is to create and action for the model of the list that is already available, so I can capture the variable and pass it in a query string to  a list that I create for the Finder method that requires an input parameter. The problem is I dont know how to do this or even if it the best way to go about solving the problem. Using a business data list and business data related list while possible is really not an option.   Thanks  

passing messageContract object to a WCF Service method using Soap - not as a method parameter

i want a web application to create a service reference to my WCF service, insert information to the header of the soap call and call my WCF method. my WCF supports soap operations (also there is an endpoint in the config). i read about MessageContract attribute and declared one in the interface file: [ServiceContract] public interface IBasicService { [OperationContract] [WebGet(UriTemplate = "GetData?value={value}")] // Add support for HTTP GET Requests string GetData(int value); } [MessageContract] public class BasicServiceHeader { [MessageHeader] public string myString; } the implementation of the contract : public class BasicService : IBasicService { public string GetData(int value) { return string.Format("You entered: {0}", value); } } i don't want the BasicServiceHeader to be passed as a parameter of GetData function , i want to keep the function signature as it is (without a BasicServiceHeader parameter) and to extract the BasicServiceHeader inside the function, (just like using soapHeader) can i do that ?

Uploading an image to a SQL DB via a SQLDataSource parameter


Hi all,

I've got a bit of a problem that I can't figure out.  I've got a SQL data source on a create user page that uploads the user data to a SQL database when the person creating the account clicks the "Next" button.  One of the columns in the DB is an "image" data type and I'm using the FileUpload control to do that.  Here is the ds and its info on the actual page:

<asp:SqlDataSource ID="sqldsAddMember" runat="server" ConnectionString="<%$ ConnectionStrings:myCS %>" InsertCommand="INSERT INTO [Member] ([UserName], [MemberImage]) VALUES (@UName, @Photo)">
        <asp:Parameter Name="UName" ConvertEmptyStringToNull="true" />
        <asp:Parameter Name="Photo" DbType="Binary" ConvertEmptyStringToNull="true" />

In the code-behind I have the following (it's something I found elsewhere on the web):

    Protected Sub CreateUserWizardStep1_Deactivate(ByVal sender As Object, ByVal e As System.EventArgs) Handles CreateUserWizardStep1.Deactivate
        sqldsAddMember.InsertParameters("UName").DefaultValue = Session("UserName&

References parameter in $create() method



Could someone please explain what exactly the references parameter of the $create() method does? my understading from reading the docs is you can pass in a reference to an already created (javascript ?)object that can then be referenced by the object being created. Is this correct? If so, how do I reference the objects passed in using this parameter in the class in question.

This page http://www.asp.net/ajax/documentation/live/clientreference/Sys/ComponentClass/ComponentCreateMethod.aspx mentions it, but does not expand on usage

Cheers Si

pass a dynamic parameter in a WCF method on HTTP GET


i have a WCF method with 2 known parameters and another one thats supposed to include a Key:Value pairs (dynamic parameter that will include an unknown number of key:value pairs).

the first question is :

i don't want to use XML as the dynamic parameter. what is the common way to pass the dynamic parameter in a WCF method? Dictionary<string,String>? json string? array of complex types? or other? ( my client - the one that uses my service, doesn't have Framework 3.5, so i suggested a framework 2.0 ways to send the parameter)

the second question :

the method  supports HTTP GET , should a dynamic parameter be passed in the URL itself or in the Header? i prefer the URL itself....


thank guys, please help ....

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