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


Post New Web Links

Writing Bitmap to Response.OutputStream - Generic Error Occured in GDI+

Posted By:      Posted Date: August 27, 2010    Points: 0   Category :ASP.Net
 

Hi,

This is what I'm trying to do when I get the error on the server (it works on my local machine):

System.Drawing.Image image = System.Drawing.Image.FromFile(filepath);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(image); 
image.Dispose();

Response.ContentType = "image/bmp";
bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Bmp);
bmp.Dispose();

I don't think it can be a permissions problem because this works on the server:

System.Drawing.Image image = System.Drawing.Image.FromFile(filepath);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(image);
image.Dispose();

Response.ContentType = "image/jpeg";
bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Dispose();

So how do I get this to work for a bitmap?

Thanks,
Dan




View Complete Post


More Related Resource Links

A generic error occured in GDI+

  

Hello, 

We have a big app running on Windows Server 2003 R2 SP2 Standard x64 Edition .

Problem is that we dont know where it happens but from time to time we have in log of errors this kind of error:

System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.

  at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
  at System.Drawing.Graphics.DrawLine(Pen pen, Int32 x1, Int32 y1, Int32 x2, Int32 y2)
  at System.Windows.Forms.GroupBox.DrawGroupBox(PaintEventArgs e)
  at System.Windows.Forms.GroupBox.OnPaint(PaintEventArgs e)
  at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
  at System.Windows.Forms.Control.WmPaint(Message& m)
  at System.Windows.Forms.Control.WndProc(Message& m)
  at System.Windows.Forms.GroupBox.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)

Do you know what can be the reason? application is not compiled for x64 platform is compiled for 'AnyCPU'.Another thing is that application is running via Citrix. And under .net framework 2.0

Activation error occured while trying to get instance of type Database, key "DBName"

  

Im using Enterprise library 5.0
I have a scenario, where I have to access two different databases in my application.

Basically this application is a webservice,delployed on my local for testing purpose.
I'm trying to access this web method from diffent windows application, default connection works fine but the other database throw's exception.

Problem is only my defaultDatabase is works fine, if I change defaultDatabase="MYCON1" with "MYCON2" it works fine, if I try to access the other database which is not default, throws exception.

<dataConfiguration defaultDatabase="MYCON1" />
<connectionStrings>
<add name="MYCON1" connectionString="Data Source=server1;Initial Catalog=dbName1;User Id=Username1;Password=password1;"
providerName="System.Data.SqlClient

" />
<add name="MYCON2" connectionString="Data Source=Server2;Initial Catalog=dbName2;User Id=Username2;Password=password2;"
providerName="System.Data.SqlClient" />
</connectionStrings>


Database myDB=EnterpriseLibraryContainer.Current.GetInstance<Database>(); --> works fine for the default database (MYCON1)


Database myDB=EnterpriseLibraryCo

A generic error occurred in GDI+.

  

Hi,

I'm getting this error on the yellow screen and I have no idea what to do with it, or where to start:


[ExternalException (0x80004005): A generic error occurred in GDI+.]
System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +377630
NopSolutions.NopCommerce.BusinessLogic.Media.PictureManager.GetPictureUrl(Picture picture, Int32 targetSize, Boolean showDefaultPicture) in F:\Temp\Test\nopCommerce 1.60\Libraries\Nop.BusinessLogic\Media\PictureManager.cs:396
NopSolutions.NopCommerce.BusinessLogic.Media.PictureManager.GetPictureUrl(Picture picture, Int32 targetSize) in F:\Temp\Test\nopCommerce 1.60\Libraries\Nop.BusinessLogic\Media\PictureManager.cs:180
NopSolutions.NopCommerce.Web.Administration.Modules.CategoryInfoControl.BindData() in F:\Temp\Test\nopCommerce 1.60\NopCommerceStore\Administration\Modules\CategoryInfo.ascx.cs:63
NopSolutions.NopCommerce.Web.Administration.Modules.CategoryInfoControl.Page_Load(Object sender, EventArgs e) in F:\Temp\Test\nopCommerce 1.60\NopCommerceStore\Administration\Modules\CategoryInfo.ascx.cs:99
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy

A generic error occurred in GDI+

  

I am getting this error at this line in my code: ImgThnail.Save(ThumbnailPath, Img.RawFormat);

Here is the entire code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;


    public static class Thumb2
    {
        public static string createThumb(this HttpServerUtility srv, string endPath, string tempPath, int relSize)
        {

            string ThumbnailPath = srv.MapPath("~\\Thumb\\" + endPath);
            string dimensions;
            using (System.Drawing.Image Img = System.Drawing.Image.FromFile(srv.MapPath("~\\" + tempPath))) 
            {
                Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, relSize);
                dimensions = Img.Width.ToString() + " x " + Img.Height.ToString();
                using (System.Drawing.Image ImgThnail = new Bitmap(Img, ThumbNailSize.Width, ThumbNailSize.Height))
                {
                    ImgThnail.Save(ThumbnailPath, Img.RawFormat);
                    ImgThnail.Dispose();
                }
                Img.Dispose();
            }
            return dimensions;
        }
        private static Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)
        {
            Size NewSize;
            double tempval;
            bool landscape;
   

Getting generic GDI error when trying to save resized image

  
Getting following error:A generic error occurred in GDI+.
Any help is appreciated.
 
Public Sub SaveImageFile(ByVal sourceImage As Bitmap, ByVal saveImagePath As [String], ByVal maxImageWidth As Integer)
            ' Resize if source image width is greater than the max:
            '--------------------------------

            If sourceImage.Width > maxImageWidth Then
                Dim bmp As Bitmap = TryCast(sourceImage, Bitmap)
                Dim newImageHeight As Integer = CInt(Math.Truncate(sourceImage.Height * (CSng(maxImageWidth) / CSng(sourceImage.Width))))
                Dim gr As Graphics = Graphics.FromImage(bmp)

                Dim bmpnew As New Bitmap(maxImageWidth, newImageHeight)
                gr.InterpolationMode = InterpolationMode.HighQualityBicubic

                gr.DrawImage(bmpnew, 0, 0, maxImageWidth, newImageHeight)
                gr.Dispose()
                bmp.Dispose()
                sourceImage.Dispose()

                'code to manipulate bmpNew goes here.

                bmpnew.Save(saveImagePath)
                '-------------------------


 


Error Occured during workflow

  
Hi, i have created a workflow using VS2010 and deployed in SP2010 but while running the workflow its giving me a status message " ERROR OCCURED" my scenario is :  once we upload a document in library it should be copy to another site's or sub site's document library.  can i create a workflow using SPD2010 for this requirement? let me know if anybody have answer.   thanks share2010        

A generic error occurred in GDI+. I am not sure what I am doing wrong please help!!

  
hello... Sorry but I get some error when I try to save an image.Here is my code If Not System.IO.Directory.Exists(DirectoryPath) Then System.IO.Directory.CreateDirectory(DirectoryPath) End If Dim FilePathName As String = DirectoryPath & "\avatar.jpg" Dim fs As New FileStream(FilePathName, FileMode.Create, FileAccess.Write) Using avatarMs As New MemoryStream(ImageBytes, 0, ImageBytes.Length) avatarMs.Write(ImageBytes, 0, ImageBytes.Length) Dim image As Image = image.FromStream(avatarMs, True)  image.Save(DirectoryPath, System.Drawing.Imaging.ImageFormat.Jpeg)'<--generic error occurred in gdi+ error appeared here End Using control.ImageUrl = DirectoryPathbasically what this code is doing is loading an an array of bytes into the memorystream(avatarMS) then converting the memory stream into an image(image) then saving the image into a folder(DirectoryPath) then displaying the image into an image control in client side... I know I am missing something here... but I don't really know what. I am not very sound in this language so if there is anything I missed out, please ask.Thanks in advanceRegards, Zephere

Get xhr object in vb.net when error occured in ajax call using JQuery.

  
Hi Dude,   I have a big problem in Jquery ajax call. I am calling the web service whenever click the update button. I have a separate web service class, in which consist of few methods. When I calling the web service method, I have made the error handling and log the error information in db after that I have to override the "ex" that means error object to XMLHttpRequest. Is it possible to assign the sqlexception to ajax object (xhr) in vb.net? Please help me its much more useful for me.   Thank in advance.

A generic error occurred in GDI+

  
Im trying to save an image on my hosting server. Locally everything works fine, but on the hosting server I get the error: "A generic error occurred in GDI+"I've already looked at this post: http://forums.asp.net/t/975883.aspxBut im unsure how to go about changing my current code below:    Public Shared Function SaveJpeg(ByVal path As String, ByVal img As Image, ByVal quality As Long) As Boolean        If ((quality < 0) OrElse (quality > 100)) Then            Return False            Throw New ArgumentOutOfRangeException("quality must be between 0 and 100.")        End If        ' Encoder parameter for image quality        Dim qualityParam As New EncoderParameter(Encoder.Quality, quality)        ' Jpeg image codec        Dim jpegCodec As ImageCodecInfo = GetEncoderInfo("image/jpeg")        Dim encoderParams As New EncoderParameters(1)        encoderParams.Param(0) = qualityParam        Try  

An unexpected error has occured

  
Hello I am using following sample code for some testing using Sharepoint 2010     SPSite siteColl = SPContext.Current.Site;     SPWeb site = SPContext.Current.Web;     string ListId = Request.QueryString["List"];     string ItemId =  Request.QueryString["ItemId"];     txtListId.Text = ListId;     txtItemId.Text = ItemId;     SPList list1 = siteColl.RootWeb.Lists["Tasks"];     Response.Write(ItemId.ToString());          SPListItem item1 = list1.Items.GetItemById(Convert.ToInt32(ItemId)); I am getting following error "An unexpected error has occured" in following line, please advise whats wrong I am doing here     SPListItem item1 = list1.Items.GetItemById(Convert.ToInt32(ItemId));

The remote server returned an unexpected response: (400) Bad Request ERROR

  
Hello I have windows application that proccess and reply to user SMS. I use a web service to send and recieve SMS.I have no access to sever and service setting and only add its reference in my application via "add Service Reference". When i call test method i get following error: "The remote server returned an unexpected response: (400) Bad Request" public void TestMethod() { OutputMessage newMessage = new OutputMessage("YYYYYYY", "XXXXXXX", MessagePriority.Medium); for (int i = 0; i < 10; i++) { ThreadStart starter = delegate() { AnotherTestMethod(newMessage); }; Thread newthread = new Thread(starter); newthread.Start(); } } private void AnotherTestMethod(OutputMessage messageToSend) { smsSoapClient _client = new smsSoapClient(); _client.Open(); string resultOfdoSendSMSCall = _client.doSendSMS("dpardazesh", "dpardazesh", "XXXXXXXX", "XXXXXXXXX", "SMS Text", true); Regex expression = new Regex("Send OK."); if (expression.IsMatch(resultOfdoSendSMSCall)) { resultOfdoSendSMSCall = resultOfdoSendSMSCall.Replace("Send OK.", string.Empty).Trim(); XDocument XmlDocument = XDocument.Parse(resultOfdoSendSMSCall); var AllMessages = from message in XmlDocument.Elements("

The remote server returned an unexpected response: (400) Bad Request ERROR

  
Hello I have windows application that proccess and reply to user SMS. I use a web service to send and recieve SMS.I have no access to sever and service setting and only add its reference in my application via "add Service Reference". When i call test method i get following error: "The remote server returned an unexpected response: (400) Bad Request" public void TestMethod() { OutputMessage newMessage = new OutputMessage("YYYYYYY", "XXXXXXX", MessagePriority.Medium); for (int i = 0; i < 10; i++) { ThreadStart starter = delegate() { AnotherTestMethod(newMessage); }; Thread newthread = new Thread(starter); newthread.Start(); } } private void AnotherTestMethod(OutputMessage messageToSend) { smsSoapClient _client = new smsSoapClient(); _client.Open(); string resultOfdoSendSMSCall = _client.doSendSMS("dpardazesh", "dpardazesh", "XXXXXXXX", "XXXXXXXXX", "SMS Text", true); } Only 2 SMS send by service. I maxReceivedMessageSize  in my app.config file but get same error again. Can anyone help me?

How to : Generic error handling function. Passing GridViewUpdatedEventArgs as EventArgs

  
Hi, I want to build a generic error handling function for handling inseted, updated, deleted events from formview, gridview and detail view. I am still a bit new to C# so I have encoutered a simple problem that I cannot resolve and cannot find an answer while searching google.Right now I handle error with validator for generic validation but I need to catch BLL error.I have different event handler for the different type of event : protected void FormView_AjoutCompte_ItemInserted(object sender, FormViewInsertedEventArgs e) { if (e.Exception != null) { Afficher_Erreur(e.Exception); e.ExceptionHandled = true; } } protected void GridView_ListeUtilisateurs_RowUpdated(object sender, GridViewUpdatedEventArgs e) { if (e.Exception != null) { Afficher_Erreur(e.Exception); e.ExceptionHandled = true; } } protected void GridView_ListeUtilisateurs_RowDeleted(object sender, GridViewDeletedEventArgs e) { if (e.Exception != null) { Afficher_Erreur(e.Exception); e.ExceptionHandled = true; } } I want to create a generic function that will handle them all, a function such as : private void GestionDerreur(EventArgs e) { if (e.Exception != null) { Afficher_Erreur(e.Exception); e.Exc

response.Outputstream problem

  
I'm trying to get create a page that grabs a file from a directory and streams the binary data to an embedded media player.   When the following code is used on a page that acts as the URL for the embedded media player the player only plays the first 11 seconds and then stops.Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim iStream As System.IO.Stream Dim strFile As String Dim strFolder As String Dim Length As Integer 'strFile = "CFD30HB1404100AD.mpeg" 'strFolder = "C:\wmdownloads" strFile = Request.QueryString("Filename") strFolder = Request.QueryString("Folder") ' Open the file. iStream = New FileStream(strFolder & "\" & strFile, FileMode.Open, FileAccess.Read, FileShare.Read) ' Total bytes to read: Length = iStream.Length Dim Buffer(CInt(Length)) As Byte iStream.Read(Buffer, 0, CInt(Length)) iStream.Close() Response.Clear() Response.ClearHeaders() Response.Charset = "UTF-8" Response.ContentEncoding = System.Text.Encoding.UTF8 Response.ContentType = "video/mpeg" Response.AddHeader("Content-Disposition", "attachment; filename=&

.NET Framework 4 Installation error - Generic Trust Failure

  
I tried to install .NET Framework 4 on Windows Server 2003, but got this error message "Generic trust failure".Part of the log:Action: Downloading and/or Verifying ItemsC:\e005b9f00558a52d0c\Windows6.0-KB956250-v6001-x86.msu: Verifying signature for Windows6.0-KB956250-v6001-x86.msuC:\e005b9f00558a52d0c\Windows6.0-KB956250-v6001-x86.msu Signature verified successfully for Windows6.0-KB956250-v6001-x86.msuC:\e005b9f00558a52d0c\Windows6.1-KB958488-v6001-x86.msu: Verifying signature for Windows6.1-KB958488-v6001-x86.msuC:\e005b9f00558a52d0c\Windows6.1-KB958488-v6001-x86.msu Signature verified successfully for Windows6.1-KB958488-v6001-x86.msuC:\e005b9f00558a52d0c\netfx_Core.mzz: Verifying signature for netfx_Core.mzzC:\e005b9f00558a52d0c\netfx_Core.mzz Signature verified successfully for netfx_Core.mzzC:\e005b9f00558a52d0c\netfx_Core_x86.msi: Verifying signature for netfx_Core_x86.msiPossible transient lock. WinVerifyTrust failed with error: 2148204800Possible transient lock. WinVerifyTrust failed with error: 2148204800C:\e005b9f00558a52d0c\netfx_Core_x86.msi - Signature verification for file netfx_Core_x86.msi (C:\e005b9f00558a52d0c\netfx_Core_x86.msi) failed with error 0x800b0100 (No signature was present in the subject.)C:\e005b9f00558a52d0c\netfx_Core_x86.msi Signature could not be verified for netfx_Core_x86.msiNo FileHash provided. Cannot perform FileHash veri

An error has occured in Workflow name ?

  
My library setting- Workflow settings - "Cancellation & Error Report" : Description shows An error has occured in Workflow name. My question is : 1. What is the meaning of the above error? 2. how can i see the detail description of this error? 3. Why this message is coming? Thank in advance for your reply, Justin  
Categories: 
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