【问题标题】:error occur when saving image to local path将图像保存到本地路径时发生错误
【发布时间】:2013-06-15 15:43:08
【问题描述】:

我得到一个图像文件,重新调整它的大小,然后在同一个文件夹中以不同的名称保存(文件名+“-resize”),但我收到了这个错误

A generic error occurred in GDI+

这是我调整大小方法的代码,

private  string resizeImageAndSave(string imagePath)
{
    System.Drawing.Image fullSizeImg
         = System.Drawing.Image.FromFile(Server.MapPath(imagePath));
    var thumbnailImg = new Bitmap(565, 290);
    var thumbGraph = Graphics.FromImage(thumbnailImg);
    thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
    thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
    thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
    var imageRectangle = new Rectangle(0, 0, 565, 290);
    thumbGraph.DrawImage(fullSizeImg, imageRectangle);
    string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath),     Path.GetFileNameWithoutExtension(imagePath) + "-resize");
    thumbnailImg.Save(targetPath, ImageFormat.Jpeg); //(A generic error occurred in GDI+) Error occur here !
    thumbnailImg.Dispose();
    return targetPath;
}

我想知道如何解决它?

【问题讨论】:

标签: c# asp.net image resize


【解决方案1】:

好像是权限问题。

更改目标文件夹的权限,以便 ASP.NET 可以写入。

请记住,保存文件的用户不是您,而是 ASP.NET 用户。

【讨论】:

    【解决方案2】:

    我认为你应该检查你写文件的许可,因为我在你的代码中找不到任何大问题。

    【讨论】:

      【解决方案3】:

      请检查正在构建的路径是什么,你可以在保存前使用下面的来确保你的目录路径存在:-

      Directory.CreateDirectory(Path.GetDirectoryName(fileName));
      

      还要考虑源文件上的问题锁定,因此您可以创建副本并处理现有参考:-

      var thumbnailImgNew = new Bitmap(thumbnailImg);
      thumbnailImg.Dispose(); 
      thumbnailImg=null;
      //Save it to target path
      thumbnailImgNew.Save(targetPath, ImageFormat.Jpeg); 
      

      【讨论】:

        【解决方案4】:

        我做了一些修改,这段代码运行良好:(在重新调整大小之前,您必须先将文件上传到您的网站。重新调整大小后,您可以删除原始文件) 第 1 步:我已将图像复制到我的应用程序中。 步骤 2:在按钮单击事件中,我已检索图像路径并提供给 re-size 功能。

        private string resizeImageAndSave(string imagePath)
            {
                System.Drawing.Image fullSizeImg
                     = System.Drawing.Image.FromFile(imagePath);
                var thumbnailImg = new Bitmap(565, 290);
                var thumbGraph = Graphics.FromImage(thumbnailImg);
                thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
                thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
                thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
                var imageRectangle = new Rectangle(0, 0, 565, 290);
                thumbGraph.DrawImage(fullSizeImg, imageRectangle);
                string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath), Path.GetFileNameWithoutExtension(imagePath) + "-resize");
                thumbnailImg.Save(targetPath, ImageFormat.Jpeg); //(A generic error occurred in GDI+) Error occur here !
                thumbnailImg.Dispose();
                return targetPath;
            }
            protected void bntUploadFile_Click(object sender, EventArgs e)
            {
                string file = Server.MapPath("tree.jpg");
                resizeImageAndSave(file);
            }
        

        【讨论】:

          【解决方案5】:

          正如其他人所说,这可能是权限问题或目录可能不存在。 但是,您可以在保存之前尝试克隆图像。如果上述不是问题,这可以解决问题。

          private static string resizeImageAndSave(string imagePath)
          {
              System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(Server.MapPath(imagePath));
              var thumbnailImg = new Bitmap(565, 290);
              var thumbGraph = Graphics.FromImage(thumbnailImg);
              thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
              thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
              thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
              var imageRectangle = new Rectangle(0, 0, 565, 290);
              thumbGraph.DrawImage(fullSizeImg, imageRectangle);
              fullSizeImg.Dispose(); //Dispose of the original image
              string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath), Path.GetFileNameWithoutExtension(imagePath) + "-resize");
              Bitmap temp = thumbnailImg.Clone() as Bitmap; //Cloning
              thumbnailImg.Dispose();
              temp.Save(targetPath, ImageFormat.Jpeg); 
              temp.Dispose();
              return targetPath;
          }
          

          【讨论】:

            【解决方案6】:

            在这行代码之后……

            string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath),     Path.GetFileNameWithoutExtension(imagePath) + "-resize");
            

            请试试这个...添加带有扩展名的图像名称

            if (!Directory.Exists(targetPath))
               Directory.CreateDirectory(targetPath);
            //now do the rest and place image name and extension...
            thumbnailImg.Save(targetPath + @"\img.jpg", ImageFormat.Jpeg); 
            thumbnailImg.Dispose();
            return targetPath;
            

            【讨论】:

              【解决方案7】:

              试试这个代码:

                  private string resizeImageAndSave(byte[] imageBytes, string fileName) {
                      var mem = new MemoryStream(imageBytes);
                      System.Drawing.Image fullSizeImg = System.Drawing.Image.FromStream(mem);
              
                      var thumbnailImg = new Bitmap(565, 290);
                      var thumbGraph = Graphics.FromImage(thumbnailImg);
                      thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
                      thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
                      thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
              
                      var imageRectangle = new Rectangle(0, 0, 565, 290);
                      thumbGraph.DrawImage(fullSizeImg, imageRectangle);
              
                      string targetPath = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileNameWithoutExtension(fileName) + "-resize.jpg");
              
                      thumbnailImg.Save(targetPath, ImageFormat.Jpeg); //(A generic error occurred in GDI+) Error occur here !
                      thumbnailImg.Dispose();
              
                      return targetPath;
                  }
              
                  protected void SaveButton_Click(object sender, EventArgs e) {
                      var inStream = Request.Files[0].InputStream;
                      var buff = new byte[inStream.Length];
              
                      inStream.Read(buff, 0, buff.Length);
              
                      resizeImageAndSave(buff, Request.Files[0].FileName);
                  }
              

              【讨论】:

                【解决方案8】:

                【讨论】:

                  【解决方案9】:

                  问题不在于位置,问题在于调整大小。

                  调整大小、裁剪图像时可能会出现 GDI 问题。 确保您的图片为 100% 的矩形大小,或者将您的图片裁剪为所需大小,然后调整其大小。

                  因此,如果您有 800x600 的图像并且您想将其调整为 450x339,您将有一个空像素,这可能会导致 GDI+ 出现错误,所以我建议您确保调整大小时的图像正确尺寸。因此,如果这可以帮助您,我创建了可以帮助我调整图像大小和裁剪图像的类。

                  public class ImageHandler
                  {
                      private Image cropImage(Image img, Rectangle cropArea)
                      {
                          Bitmap bmpImage = new Bitmap(img);
                          if (bmpImage.Size.Width < cropArea.Width)
                              cropArea.Width = bmpImage.Size.Width;
                          if (bmpImage.Size.Height < cropArea.Height)
                              cropArea.Height = bmpImage.Size.Height;
                          Bitmap bmpCrop = bmpImage.Clone(cropArea,
                                                          bmpImage.PixelFormat);
                          return (Image)(bmpCrop);
                      }
                  
                      private Image resizeImage(Image imgToResize, Size size)
                      {
                          int sourceWidth = imgToResize.Width;
                          int sourceHeight = imgToResize.Height;
                  
                          float nPercent = 0;
                          float nPercentW = 0;
                          float nPercentH = 0;
                  
                          nPercentW = ((float)size.Width / (float)sourceWidth);
                          nPercentH = ((float)size.Height / (float)sourceHeight);
                  
                          if (nPercentH < nPercentW)
                              nPercent = nPercentH;
                          else
                              nPercent = nPercentW;
                  
                          int destWidth = (int)(sourceWidth * nPercent);
                          int destHeight = (int)(sourceHeight * nPercent);
                  
                          Bitmap b = new Bitmap(destWidth, destHeight);
                          Graphics g = Graphics.FromImage((Image)b);
                          g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                  
                          g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
                          g.Dispose();
                  
                          return (Image)b;
                      }
                      public Image ResizeWithCrop(Image imgToResize, Size size, bool center = true)
                      {
                          int sourceWidth = imgToResize.Width;
                          int sourceHeight = imgToResize.Height;
                  
                          float nPercent = 0;
                          float nPercentW = 0;
                          float nPercentH = 0;
                  
                          nPercentW = ((float)size.Width / (float)sourceWidth);
                          nPercentH = ((float)size.Height / (float)sourceHeight);
                  
                          if (nPercentH < nPercentW)
                              nPercent = nPercentW;
                          else
                              nPercent = nPercentH;
                          float resultWidth = sourceWidth * nPercent;
                          float resultHeight = sourceHeight * nPercent;
                          int destWidth = (int)resultWidth;
                          int destHeight = (int)resultHeight;
                          Bitmap b = new Bitmap(destWidth, destHeight);
                          Graphics g = Graphics.FromImage((Image)b);
                          g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                  
                          g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
                          g.Dispose();
                          int restWidth = destWidth - size.Width;
                          int restHeight = destHeight - size.Height;
                  
                          int pX = center ? restWidth > 0 ? (int)(restWidth / 2) : 0 : 0;
                          int pY = center ? restHeight > 0 ? (int)(restHeight / 2) : 0 : 0;
                          return cropImage((Image)b, new Rectangle(pX, pY, size.Width, size.Height));
                  
                  
                      }
                      public void SaveJpeg(string path, Image img, long quality = 85L)
                      {
                          try
                          {
                  
                  
                          EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                  
                          ImageCodecInfo jpegCodec = getEncoderInfo(@"image/jpeg");
                  
                          EncoderParameters encoderParams
                          = new EncoderParameters(1);
                  
                          encoderParams.Param[0] = qualityParam;
                  
                          System.IO.MemoryStream mss = new System.IO.MemoryStream();
                  
                          System.IO.FileStream fs
                          = new System.IO.FileStream(path, System.IO.FileMode.Create
                          , System.IO.FileAccess.ReadWrite);
                  
                          img.Save(mss, jpegCodec, encoderParams);
                          byte[] matriz = mss.ToArray();
                          fs.Write(matriz, 0, matriz.Length);
                  
                          mss.Close();
                          fs.Close();
                          }
                          catch (Exception ex)
                          {
                  
                          }
                      }
                  
                      private ImageCodecInfo getEncoderInfo(string mimeType)
                      {
                          // Get image codecs for all image formats
                          ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                  
                          // Find the correct image codec
                          for (int i = 0; i < codecs.Length; i++)
                              if (codecs[i].MimeType == mimeType)
                                  return codecs[i];
                          return null;
                      }
                  
                      public void SavePng(string path, Image img, long quality = 85L)
                      {
                          try
                          {
                              EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                  
                              ImageCodecInfo jpegCodec = getEncoderInfo(@"image/png");
                  
                              EncoderParameters encoderParams
                              = new EncoderParameters(1);
                  
                              encoderParams.Param[0] = qualityParam;
                  
                              System.IO.MemoryStream mss = new System.IO.MemoryStream();
                  
                              System.IO.FileStream fs
                              = new System.IO.FileStream(path, System.IO.FileMode.Create
                              , System.IO.FileAccess.ReadWrite);
                  
                              img.Save(mss, jpegCodec, encoderParams);
                              byte[] matriz = mss.ToArray();
                              fs.Write(matriz, 0, matriz.Length);
                  
                              mss.Close();
                              fs.Close();
                          }
                          catch (Exception ex)
                          {
                  
                          }
                      }
                  }
                  

                  【讨论】:

                    【解决方案10】:

                    关于这一行:

                    string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath),     Path.GetFileNameWithoutExtension(imagePath) + "-resize");
                    

                    您确定原始 imagePath 中没有多次出现不带扩展名的文件名吗?这可能会导致问题,例如没有定位到正确的文件夹。

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2020-08-22
                      • 2013-09-26
                      • 1970-01-01
                      • 2021-02-07
                      相关资源
                      最近更新 更多