Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6921497
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T10:17:04+00:00 2026-05-27T10:17:04+00:00

i made the image re size Handler. i am getting this Exception. HttpApplication.ExecuteStep =>

  • 0

i made the image re size Handler. i am getting this Exception.

“HttpApplication.ExecuteStep =>
CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute
=> ImageHandler.ProcessRequest|System.ArgumentException: Parameter is not valid. at System.Drawing.Bitmap..ctor(Int32 width, Int32
height, PixelFormat format) at
Holmgrens.ImageResize.IMGHandller.ImageHandler.ProcessRequest(HttpContext
context)”.

Here is my code.

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Drawing;
using System.IO;

namespace Xyz.ImageResize.IMGHandller
{
    public class ImageHandler : IHttpHandler
    {

        // incoming query string variables

        private string imagePath = string.Empty;        // path=    virtual path required

        private string imageWidth = "0";                // w=   0 means use original

        private string imageHeight = "0";               // h=

        private string imageQuality = "0";              // q=

        private string constrainProportions = "true";   // cp=  true or false

        private string rotation = "0";                  // r= rotation in degrees, optional, 0 is default.



        private const Int32 maxQuality = 100;

        private const Int32 minQuality = 30;

        private const string imageNotFound = "~/SlideData/TempImg/Desert.jpg";

        private string mimeType = "image/jpeg";

        //get imag config item
        //ImageConfiguration imgconsetting = new ImageConfiguration();





        public void ProcessRequest(HttpContext context)
        {

            try
            {

                // get query string parameters           

                imagePath = context.Request.QueryString["path"];

                imageWidth = context.Request.QueryString["w"];

                imageHeight = context.Request.QueryString["h"];

                imageQuality = context.Request.QueryString["q"];

                constrainProportions = context.Request.QueryString["cp"];

                rotation = context.Request.QueryString["r"];

                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(imagePath)))
                {

                    imagePath = HttpContext.Current.Server.MapPath(imagePath);

                }

                else
                {

                    // displays an empty image holder or make sure you have a not found image

                    imageQuality = "100";

                    imagePath = HttpContext.Current.Server.MapPath(imageNotFound);

                }

                //get file info

                FileInfo fi = new FileInfo(imagePath);
                if (fi.Extension.ToLower() == ".gif")
                    mimeType = "image/gif";
                else if (fi.Extension.ToLower() == ".png")
                    mimeType = "image/png";
                else
                    mimeType = "image/jpeg";

                // sets the HTTP MIME type of the output stream.

                // jpeg is default       

                context.Response.ContentType = mimeType;



                // clear all content output from the buffer stream

                context.Response.Clear();



                // response is cacheable by clients and shared (proxy) caches
                context.Response.Expires = 24 * 60; //one day;
                string ETag = Hash.GetHash(string.Format("{0}{1}", imagePath, fi.LastWriteTimeUtc.ToString()), Hash.HashType.MD5);
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                context.Response.Cache.SetLastModified(fi.LastWriteTimeUtc);
                context.Response.Cache.SetETag(string.Format("\"{0}\"", ETag));




                // Buffer response so that page is sent

                // after processing is complete.

                context.Response.BufferOutput = true;





                //if image height is zero,calculate the image height with aspect ration of image
                if (imageHeight == "0")
                {
                    imageHeight = ImageHeightWithAspect(imagePath, Convert.ToInt16(imageWidth)).ToString();

                }



                Int32 originalWidth = 0;

                Int32 originalHeight = 0;

                Int32 newWidth = 0;

                Int32 newHeight = 0;

                Int64 quality = 0;



                // set the quality of the jpeg image returned.. 30 (low) - 100 (high)

                if (Int64.TryParse(imageQuality, out quality))
                {

                    if (quality > maxQuality) { quality = maxQuality; }

                    if (quality < minQuality) { quality = minQuality; }

                }

                else

                { quality = maxQuality; }



                // ENCODING

                System.Drawing.Imaging.Encoder encoder =

                  System.Drawing.Imaging.Encoder.Quality;



                System.Drawing.Imaging.EncoderParameter encoderParameter =

                    new System.Drawing.Imaging.EncoderParameter(encoder, quality);



                // create an array with one parameter; quality

                System.Drawing.Imaging.EncoderParameters codecParams =

                    new System.Drawing.Imaging.EncoderParameters(1);

                codecParams.Param[0] = encoderParameter;



                // Gets the codecs for this image type (jpeg)

                System.Drawing.Imaging.ImageCodecInfo codecInfo = getEncoderInfo();



                // Create a bitmap to hold new image, uses Bitmap.GetThumbnailImage

                using (System.Drawing.Bitmap bitmapOriginal = new System.Drawing.Bitmap(imagePath))
                {

                    originalWidth = bitmapOriginal.Width;

                    originalHeight = bitmapOriginal.Height;



                    Int32.TryParse(imageWidth, out newWidth);

                    Int32.TryParse(imageHeight, out newHeight);



                    if (newWidth > originalWidth) { newWidth = originalWidth; }

                    if (newHeight > originalHeight) { newHeight = originalHeight; }



                    // Constrain Proportions provides scaling by width

                    // False by default which forces width and height - when exact size required

                    if (!string.IsNullOrEmpty(constrainProportions)

                        && constrainProportions.Equals("true", StringComparison.OrdinalIgnoreCase))
                    {

                        newWidth = Convert.ToInt32(imageWidth);

                        Double scaleFactor = 0.0;

                        // scale the image based on the width

                        if (originalWidth > originalHeight)
                        {

                            // landscape

                            Int32 largestDimension = (Math.Max(originalWidth, originalHeight));

                            scaleFactor = ((Double)newWidth / (Double)largestDimension);

                        }

                        else
                        {

                            // portrait

                            Int32 smallestDimension = (Math.Min(originalWidth, originalHeight));

                            scaleFactor = ((Double)newWidth / (Double)smallestDimension);

                        }

                        newHeight = Convert.ToInt32((originalHeight * scaleFactor));

                    }



                    // Create the new bitmap image

                    using (System.Drawing.Bitmap bitmapNew = new System.Drawing.Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
                    {

                        // use the same resolution

                        bitmapNew.SetResolution(bitmapOriginal.HorizontalResolution, bitmapOriginal.VerticalResolution);



                        // Create the graphics object to draw the old bitmap on the new sized bitmap.

                        using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmapNew))
                        {

                            // resize using the highest possible quality for best results

                            graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;



                            graphic.DrawImage(bitmapOriginal,

                                new System.Drawing.Rectangle(-1, -1, newWidth + 1, newHeight + 1), // destination

                                new System.Drawing.Rectangle(0, 0, originalWidth, originalHeight), //source

                                System.Drawing.GraphicsUnit.Pixel); //using pixels
                            graphic.Dispose();

                        }



                        // Rotate the bitmap

                        switch (Convert.ToInt32(rotation))
                        {

                            case 90:

                                bitmapNew.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);

                                break;

                            case 180:

                                bitmapNew.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

                                break;

                            case 270:

                                bitmapNew.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);

                                break;

                            default:

                                // always show as original

                                bitmapNew.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipNone);

                                break;

                        }



                        // context.Response.OutputStream enables binary output to the outgoing HTTP content body.

                        // codecInfo is the image type (jpeg)

                        // codecParams is the quality
                        Bitmap bm = new Bitmap(bitmapNew);
                        bitmapNew.Dispose();
                        //bm.Save(context.Response.OutputStream, codecInfo, codecParams);                    
                        //bm.Dispose();
                        using (MemoryStream stream = new MemoryStream())
                        {
                            bm.Save(stream, codecInfo, codecParams);
                            stream.WriteTo(context.Response.OutputStream);
                            stream.Dispose();
                        }
                        bm.Dispose();

                    }
                    bitmapOriginal.Dispose();

                }
                encoderParameter.Dispose();
                codecParams.Dispose();
            }
            catch(Exception ex)
            {
                response.write(ex);

            }

        }



        /// <summary>

        /// Return the codec info for jpeg images

        /// </summary>

        /// <param name="mimeType"></param>

        /// <returns></returns>

        private System.Drawing.Imaging.ImageCodecInfo getEncoderInfo()
        {

            System.Drawing.Imaging.ImageCodecInfo[] encoders;

            encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();



            Int32 i = 0;

            while (i < encoders.Length)
            {

                if (encoders[i].MimeType == mimeType)
                {

                    return encoders[i];

                }

                i++;

            }



            return null;

        }



        public bool IsReusable

        { get { return true; } }


        private int ImageHeightWithAspect(string fileName,int newWidth)
        {

            Image original = Image.FromFile(fileName);

            //Find the aspect ratio between the height and width.

            float aspect = (float)original.Height / (float)original.Width;

            //Calculate the new height using the aspect ratio

            // and the desired new width.

            int newHeight = (int)(newWidth * aspect);            

            //Dispose of our objects.

            original.Dispose();
            return newHeight;



        }
    }
}

please guide me how to remove this exception.

thanks
Humayoo

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T10:17:05+00:00Added an answer on May 27, 2026 at 10:17 am

    Either your newWidth or newHeight is incorrect in this line:

    using (System.Drawing.Bitmap bitmapNew = new System.Drawing.Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
    

    You need to debug your application to determine what the incorrect value is and how to fix it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've made an image upload script using the move_uploaded_file function. This function seems to
Can someone help me on this. I'm made an image uploader and i want
I had a small image 250x208 (size decreased from 960x800) and made 9.png out
I made an image to easier explain what Im after: Image Illustration http://bayimg.com/image/eabahaaci.jpg Ive
I have made a image gallery with jQuery found here: http://sarfraznawaz2005.kodingen.com/demos/jquery/image_gallery/ I just wanted
I have made a SVG image, or more like mini application, for viewing graphs
I've made a script which copies the alt attribute of an image and puts
Save one image path in the database... and whenever a call is made to
I made this code with jQuery to fade images ( but not the one
When using PNG files (made with Paint.NET) as background images on my web site,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.