Click here to Skip to main content
15,905,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I've got a problem when uploading images using asp.net, shortly explain is...
Loop to get each picture in HttpPostedFile. Then calculate color for adding text to it
The error will occur on the second or some time third loop at "System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(myimage);"

Any body had experienced through this before, please suggest, would be many thanks.

This is my codes:
C#
private void saveFile(HttpPostedFile hpf, string strFileName)
        {
            System.Drawing.Image myimage = System.Drawing.Image.FromStream(hpf.InputStream, false, false);
            int imageSize = hpf.ContentLength;
            hpf = null;
            colorProcessing cp = averageColor(cropImage(myimage));
            addText(myimage,cp);
            
            myimage.Save(Server.MapPath("~/PlantsPhoto/") + strFileName);
            myimage.Dispose();
            System.Threading.Thread.Sleep(imageSize / 10);
        }

        public void addText(System.Drawing.Image myimage, colorProcessing cp)
        {

            var w = myimage.Width;
            var h = myimage.Height;
            double gaugeSize = h >= w ? h / 100 : w / 100;
            double fontSize = ((gaugeSize / 10) * (10 - (gaugeSize / 10))) + 4;
            System.Drawing.StringFormat strFormat = new System.Drawing.StringFormat();
            strFormat.Alignment = System.Drawing.StringAlignment.Near;
            strFormat.LineAlignment = System.Drawing.StringAlignment.Near;
            System.Drawing.Brush b= cp.colorTone!=0?System.Drawing.Brushes.White:System.Drawing.Brushes.Black;
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(myimage);
            
            g.DrawString("xx©Copyright", new System.Drawing.Font("Tahoma", (int)fontSize), b,
                new System.Drawing.RectangleF(0, 0, w / 2, h / 2), strFormat);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            g.Dispose();
            myimage.Dispose();
            strFormat.Dispose();
            cp.Dispose();// = null;
            b.Dispose();
        }
        private System.Drawing.Bitmap cropImage(System.Drawing.Image img)
        {
            System.Drawing.Rectangle cropArea = new System.Drawing.Rectangle(0,0,img.Width / 2, img.Height/3);
            System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(img);
            System.Drawing.Bitmap bmpCrop = bmpImage.Clone(cropArea,bmpImage.PixelFormat);
            //bmpCrop.Save(Server.MapPath("~/PlantsPhoto/") + "ssss.jpg");
            bmpImage.Dispose();
            //img.Dispose();
            
            return bmpCrop;
        }
        public colorProcessing averageColor(System.Drawing.Bitmap img)
        {
            System.Drawing.Bitmap MyBitmap = img; 
            System.Drawing.Rectangle Rect = new System.Drawing.Rectangle(0, 0, MyBitmap.Width, MyBitmap.Height);
            System.Drawing.Imaging.BitmapData BmpData = MyBitmap.LockBits(Rect,
                                               System.Drawing.Imaging.ImageLockMode.ReadOnly,
                                               MyBitmap.PixelFormat);


            int Size = BmpData.Stride * MyBitmap.Height;
            byte[] RGBs = new byte[Size];


            IntPtr Pointer = BmpData.Scan0;
            System.Runtime.InteropServices.Marshal.Copy(Pointer, RGBs, 0, Size);


            MyBitmap.UnlockBits(BmpData);


            // we've got all the RGB values in an array
            int Sum = 0;
            int whiteCount=0;
            for (int Index = 0; Index < RGBs.Length; Index++)
            {
                Sum += RGBs[Index];
                if (RGBs[Index]<50)
                {
                    whiteCount++;
                }
            }

            // higher Average means a lighter picture (255 = white, 0 = black)
            int Average = Sum / RGBs.Length;
            colorProcessing CPInfo = new colorProcessing();
            CPInfo.avgColor = Average;
            CPInfo.colorTone = (RGBs.Length / 15) > whiteCount ? colorProcessing.tone.White : colorProcessing.tone.Black;
            MyBitmap.Dispose();
            BmpData = null;
            RGBs = null;
            return CPInfo;
        }
Posted
Updated 9-Feb-14 20:59pm
v5
Comments
Kornfeld Eliyahu Peter 10-Feb-14 3:19am    
It seems that the image format doesn't fit for System.Drawing...
http://msdn.microsoft.com/en-us/library/system.drawing.graphics.fromimage(v=vs.110).aspx
jack_th 10-Feb-14 4:17am    
Format may be concerned but I have already done a test on random orderly select 4 files to upload by considerate on the same picture which does not error at the last time but get error on later time.The result means, it's not in this error case.
Kornfeld Eliyahu Peter 10-Feb-14 4:33am    
public static Graphics FromImage(Image image)
{
if (image == null)
{
throw new ArgumentNullException("image");
}
if ((image.PixelFormat & PixelFormat.Indexed) != PixelFormat.Undefined)
{
throw new Exception(SR.GetString("GdiplusCannotCreateGraphicsFromIndexedPixelFormat"));
}
IntPtr zero = IntPtr.Zero;
int num = SafeNativeMethods.Gdip.GdipGetImageGraphicsContext(new HandleRef(image, image.nativeImage), out zero);
if (num != 0)
{
throw SafeNativeMethods.Gdip.StatusException(num);
}
return new Graphics(zero)
{
backingImage = image
};
}

This is the code for the FromImage method...
The only way to get your exception is when GdipGetImageGraphicsContext returns 2.
The possible fails are...

This constructor fails if the Image object is based on a metafile that was opened for reading. The Image::Image(file) and Metafile::Metafile(file) constructors open a metafile for reading. To open a metafile for recording, use a Metafile constructor that receives a device context handle.
This constructor also fails if the image uses one of the following pixel formats:
PixelFormatUndefined
PixelFormatDontCare
PixelFormat1bppIndexed
PixelFormat4bppIndexed
PixelFormat8bppIndexed
PixelFormat16bppGrayScale
PixelFormat16bppARGB1555

Use Image.PixelFormat to check...
jack_th 11-Feb-14 21:35pm    
In my codes, it notices that SafeNativeMethods does not exist in the namespace "System.Drawing". I already done search on google but there were no example make me understood. I am a very new in Drawing namespace. Please show some example or explain about SafeNativeMethods more. Thank you.
Kornfeld Eliyahu Peter 12-Feb-14 2:08am    
The code I posted is the code for System.Drawing.Graphics.FromImage static method - it's here only to explain you the possible paths of failure...
Now stop a bit and try to answer the question -
There are images with pixel format from the above list? (hint: use debugger)

1 solution

I've try to use keyword 'at system.drawing.graphics.checkerrorstatus(int32 status)' until I found this thread >> 'Actually the problem is a bug in the .NET Graphics object when you use a brush from System.Drawing.Brushes. Create a new SolidBrush instead and I bet the problem will go away.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900