2011-12-07 64 views
0

我做了图像重新大小处理程序。我得到这个例外。我得到这个异常“参数无效.at System.Drawing.Bitmap..ctor(Int32宽度,Int32高度,PixelFormat格式)”

“HttpApplication.ExecuteStep => CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute => ImageHandler.ProcessRequest | System.ArgumentException:在System.Drawing.Bitmap..ctor参数无效。 (Int32宽度,Int32 高度,PixelFormat格式)在 Holmgrens.ImageResize.IMGHandller.ImageHandler.ProcessRequest(HttpContext 上下文)“。

这是我的代码。

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; 



     } 
    } 
} 

请指导我如何删除此例外。

感谢 Humayoo

+0

什么是高度和宽度值,可能类似于[位图参数无效 - 参数异常](http://stackoverflow.com/questions/5801652/bitmap-while-assigning-height-width-crashes/ 5802113#5802113) – V4Vendetta

回答

1

无论您newWidth或newHeight是在这一行不正确:

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

您需要调试您的应用程序,以确定哪些不正确的值,以及如何解决它。

相关问题