C# - "Parameter Is Not Valid" Exception From System.Drawing.Image.FromStream() Method?
Aug 27, 2010
I got a hard time with the Image.FromStream method in my website. The code below works perfect on my computer. But when I uploaded it to the test server, it always gives me "Parameter not valid" exception.
if (!afuImageFile.IsUploading && afuImageFile.HasFile)
{
System.Drawing.Image imgFile = System.Drawing.Image.FromStream(afuImageFile.FileContent);
}
the afuImageFile is an AsynFileUploader control in Ajax Tool Kits. afuImageFile.FileContent is a HttpInputStream.
I have implemented the following functionality that connects to webservice and downloads a favicon from a given site and saves it to a byte[] which I store in our database. I now want to set it up so that it saves the icon to the disk. However I am getting a "Parameter is not valid" when I try and create the image from the byte[].My code is as follows..
The exception occurs on the middle line. This code works perfectly 9 times out of ten, but for some favicons, even thought the icon is a valid image (or at least it appears to be and it shows in the browser when point at it) I get this exception. Does anyone have any ideas? I am pulling my hair out here!
All of a sudden I started getting this nasty exception all over the place:
The type initializer for 'System.Drawing.ToolboxBitmapAttribute' threw an exception.
Some relevant observations: * The error started occuring a few hours after the last deployment to the live server, not immediately after. So it basically started occuring of its own accord.
* We have recently moved to a new host (a VPS). The error only occurs on that server, not our local server nor at the old host's (which was a shared environment).
* The problem is basically the same as this: [URL]
* I tried reinstalling Ajax extensions, then our website in IIS, then finally the .Net 2 framework. But the error still occurs after all this.
* The error occurs on line 1, which is just the page directive: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Test.WebForm1" %>
I'm finding it difficult to get a decent trace, but here is one that our CMS provided:
The type initializer for 'System.Drawing.ToolboxBitmapAttribute' threw an exception. at System.Web.UI.TemplateParser.ProcessException(Exception ex) at System.Web.UI.TemplateParser.ParseStringInternal(String text, Encoding fileEncoding) at System.Web.UI.TemplateParser.ParseString(String text, VirtualPath virtualPath, Encoding fileEncoding) at System.Web.UI.TemplateParser.ParseFile(String physicalPath, VirtualPath virtualPath) at System.Web.UI.TemplateParser.ParseInternal() at System.Web.UI.TemplateParser.Parse() at System.Web.Compilation.BaseTemplateBuildProvider.get_CodeCompilerType() at System.Web.Compilation.BuildProvider.GetCompilerTypeFromBuildProvider(BuildProvider buildProvider) at System.Web.Compilation.BuildProvidersCompiler.ProcessBuildProviders() at System.Web.Compilation.BuildProvidersCompiler.PerformBuild() at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) at System.Web.UI.TemplateControl.LoadControl(VirtualPath virtualPath) at System.Web.UI.TemplateControl.LoadControl(String virtualPath) at umbraco.macro.loadUserControl(String fileName, Hashtable attributes, page umbPage)
My own code doesn't use the ToolboxBitmapAttribute, but third party products like Peter Blum's and Telerik's do.
Peter Blum replied with some useful hints:
* The "type initializer" concept probably needs some research, but I'm guessing that is an important clue. A quick web search of "type initializer" finds many situations it occurs for a variety of classes.
* The stack trace suggests that this is happening as ASP.NET is compiling your web form. The error is happening as the ASP.NET parser runs. Again this is external from my code (even creating or "type initializing" the attribute is not something my code does).
How to add System.Drawing.Image object to Asp:Image Control but I dint have imageId in my table.Image field is in another table..i retrieve image from database in Image object.i want to display it in asp:Image control or grid view.how to do it?
System.Drawing.Image newImage; using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length)) { ms.Write(imageBytes, 0, imageBytes.Length); newImage = System.Drawing.Image.FromStream(ms, true); }
and now I need to have this image as a source for asp:Image (System.Web.UI.WebControls.Image). Is this possible as I know that conversion is impossible?
I am developing an application that stores images as Base64 strings in xml files. I also want to allow the user to crop the image before saving it to the file, preferably all in memory without having to save a temp file, and then delete it afterwards. In order to display the newly uploaded image, I need to create a HTTP handler that I can bind the asp:Image to. The only examples for doing this online require passing the .ashx an ID and then pulling the image from a DB or other data store. Is it possible to somehow pass the raw data to the .ashx in order to get back the image?
I want to write a unit tetsing code for this function
[Code]....
I'd like to cretae a stub for image As System.Drawing.Image, set expectation as image.Width=250, image.Height=200. Can anyone help me on how to create the image stub in Rhino Mocks?[Code]....
I have a byteArray which I can only convert into an Image (Drawing.Image) I was wondering how I can display it a webpage. I used memoryStream as I dont want to user to have to download the image. Eventually I will use this to display images in google maps.. I can convert it into a graphic but once again not sure what I will do with it. The Error I have been getting lately is Cannot implicitly convert type 'System.Drawing.Image' to 'System.Web.UI.WebControls.ImageField'
I have a photo on my server image1.jpg in high resolution, and I need it to be resized everytime it is send to client depending with dimension I put but should not make extra file on disk.
I used aspjpeg for this in past but now I need something that can be used on servers that do not have aspjpeg instaled.
I get this Microsoft .NET Framework start up error. when i try to run a window project.
i am working on visual studio2005 (.NET FRAMEWORK2.0).
i am working on win 7 machine & i am not able to edit machine.config file.coz it is read only type.
below is the error ....
See the end of this message for details on invoking just-in-time (JIT) debugging instead of this dialog box.
Exception Text
System.ArgumentException: Parameter is not valid. at System.Drawing.Bitmap..ctor(String filename) at HumanHistology.frmquiz1.FillOptions() at HumanHistology.frmquiz1.btnnext_Click(Object sender, EventArgs e) at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
I'm using a slightly modified version of Valum's upload [github link], I've modified it to upload to a database but haven't modified the javascript that it is using to get the file into the Request as an InputStream. The following line of code is failing in IE 8 but is confirmed to work in Chrome. using (Image imgInput = Image.FromStream(Request.InputStream)) The error received is "Parameter not valid". It appears to be having an issue with the Input Stream being used but it exists/has data (not sure how to validate if the data is good or not).
Page <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Upload-Pictures</h2> <div id="file-uploader"> <noscript> <p>Please enable JavaScript to use file uploader.</p> </noscript> </div> <script src="/Scripts/fileuploader.js" type="text/javascript"></script> <script type="text/javascript"> function createUploader() { var uploader = new qq.FileUploader({ element: document.getElementById('file-uploader'), action: '/Admin/FileUpload/' + <%= Model.PropertyId %>, debug: true }); } window.onload = createUploader; </script> </asp:Content> Controller [AcceptVerbs(HttpVerbs.Post)] public JsonResult FileUpload(int id) { try { byte[] newImageByteArray = GetByteArrayForResizedImage(350, Request.InputStream); byte[] thumbnailByteArray = GetByteArrayForResizedImage(150, Request.InputStream); //Add to DB } catch (Exception ex) { // This is where the exception is caught return Json(new { success = false, message = ex.Message }, "application/json"); } return Json(new { success = true }, "application/json"); } private static byte[] GetByteArrayForResizedImage(int imageSize, Stream inputStream) { byte[] imageByteArray; // For some reason in IE the inputStream here is causing it to crash using (Image imgInput = Image.FromStream(inputStream)) { //Image processing } return imageByteArray; } fileuploader.js - qq.FileUploader /** * Class that creates upload widget with drag-and-drop and file list * @inherits qq.FileUploaderBasic */ qq.FileUploader = function(o){ // call parent constructor qq.FileUploaderBasic.apply(this, arguments); // additional options qq.extend(this._options, { element: null, // if set, will be used instead of qq-upload-list in template listElement: null, template: '<div class="qq-uploader">' + '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' + '<div class="qq-upload-button">Upload a file</div>' + '<ul class="qq-upload-list"></ul>' + '</div>', // template for one item in file list fileTemplate: '<li>' + '<span class="qq-upload-file"></span>' + '<span class="qq-upload-spinner"></span>' + '<span class="qq-upload-size"></span>' + '<a class="qq-upload-cancel" href="#">Cancel</a>' + '<span class="qq-upload-failed-text">Failed</span>' + '</li>', classes: { // used to get elements from templates button: 'qq-upload-button', drop: 'qq-upload-drop-area', dropActive: 'qq-upload-drop-area-active', list: 'qq-upload-list', file: 'qq-upload-file', spinner: 'qq-upload-spinner', size: 'qq-upload-size', cancel: 'qq-upload-cancel', // added to list item when upload completes // used in css to hide progress spinner success: 'qq-upload-success', fail: 'qq-upload-fail' } }); // overwrite options with user supplied qq.extend(this._options, o); this._element = this._options.element; this._element.innerHTML = this._options.template; this._listElement = this._options.listElement || this._find(this._element, 'list'); this._classes = this._options.classes; this._button = this._createUploadButton(this._find(this._element, 'button')); this._bindCancelEvent(); this._setupDragDrop(); }; fileuploader.js - qq.FileUploaderBasic /** * Creates upload button, validates upload, but doesn't create file list or dd. */ qq.FileUploaderBasic = function(o){ this._options = { // set to true to see the server response debug: false, action: '/server/upload', params: {}, button: null, multiple: true, maxConnections: 3, // validation allowedExtensions: [], sizeLimit: 0, minSizeLimit: 0, // events // return false to cancel submit onSubmit: function(id, fileName){}, onProgress: function(id, fileName, loaded, total){}, onComplete: function(id, fileName, responseJSON){}, onCancel: function(id, fileName){}, // messages messages: { typeError: "{file} has invalid extension. Only {extensions} are allowed.", sizeError: "{file} is too large, maximum file size is {sizeLimit}.", minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.", emptyError: "{file} is empty, please select files again without it.", onLeave: "The files are being uploaded, if you leave now the upload will be cancelled." }, showMessage: function(message){ alert(message); } }; qq.extend(this._options, o); // number of files being uploaded this._filesInProgress = 0; this._handler = this._createUploadHandler(); if (this._options.button){ this._button = this._createUploadButton(this._options.button); } this._preventLeaveInProgress(); };
I am trying to display an image from database, and I keep ending up with an error Parameter is not valid. Bitmap bm2 = new Bitmap(targetW, targetH);
I have tried different ways but I can't get it to work (as you can see in my commented code). I am having trouble on the saving it to the database process, displaying it isn't a problem (when I had valid images)
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.
Im my MVC 3.0 Application, I created a helper like below;
[Code]....
And I used that helper in a linq query as below;
[Code]....
When I fire my app, it gives me the below error. LINQ to Entities does not recognize the method 'System.String GenerateURl(System.String)' method, and this method cannot be translated into a store expression. 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.NotSupportedException: LINQ to Entities does not recognize the method 'System.String GenerateURl(System.String)' method, and this method cannot be translated into a store expression. Source Error:
Line 43: public Blogs GetBlog(string urlstring) { Line 44: Line 45: return GetAll().SingleOrDefault(x => BlogUrlGeneration.GenerateURl(x.ArticleTitle).Equals(urlstring)); Line 46: } Line 47:
İn my blog, the link will be like below; [URL] so I need to set the above urlgenerator class into lambada. How can I do that? What would it take to make that work perfectly
When I move some web-based code from VS2008 to VS2010, I find it is different when it is hard to handle the Image class.
Let's take the following code as an example.
[Code]....
As I have already imported the System.Drawing namespace, I still cannot use Image.FromFile method as VS2010 detectss the Image class is in System.Web.UI.WebControls namespace.I have lots of such a kind of code in my project using Image class and I will get messed if need to modify the code from
Using C# I was trying to develop the following two. The way I am doing it may have some problem and need your kind advice. In addition, I dont know whether there is any existing method to do the same.
How do i import system.drawing into a page. I created a page called pie chart.aspx but instead of just using image of a pie chart i want to use the system.drawings to create a pie chart with atleast 3 distributions or more like, red, green and blue or something. how do i accomplish that. I tried youtubeing and google but nothing really worked. I know its suppose to be in code behind page but how??/
I am using the following code to draw text onto a jpg image but it requires x/y coordinate percision on where to place the text.
[code]....
How would I go about centering text onto an image? I am guessing it would have to do with defining some sort of container (rectangle maybe?) that is the width of the image and centering the text within that? Not sure what the best practice would be for this.
Does anyone know if the following is possible and if so what the best way of doing it is for free? I am generating a PrintDocument in a project I am currently working on and displaying a print dialog box so a user can choose which printer they want to use etc. The is currently a windows form application and if a user wants to print to a PDF they can select to print to CutePDF or something similar. However I am now putting a ASP.Net web frontend on the application and want to use the same code to generate the PrintDocument but want to print it to a PDF on the fly and serve it up via the Response stream in the format of a PDF download. So my question is....How can I use the current PrintDocument and generate a PDF in memory from it?
I am importing data from Excel sheet to a database. The table in the database has a special column where I store Interior.ColorIndex of each row in Excel. Then I display the data in a GridView. I need its rows to have the same or close colors as corresponding rows in Excel. I cannot find how to convert the color information I store in my database into System.Drawing.Color (in other words, to RGB) to apply to my GridView.