【问题标题】:Recommended method for fast, and safe server side image resizing快速、安全的服务器端图像大小调整的推荐方法
【发布时间】:2013-03-14 13:29:19
【问题描述】:

我目前有使用 GDI (System.Drawing) 的工作代码。但我正在考虑将其转换为使用 System.Windows.Media.ImagingImageMagick

我担心这不应该泄漏内存,应该是线程安全的、多线程的并且应该提供高质量的结果。 ImageMagick 似乎提供了所有这些。但是,System.Windows.Media.Imaging 已被建议作为“更清洁”的解决方案。

你知道这两种方法有什么陷阱吗?

我还有其他选择吗?

【问题讨论】:

    标签: c# .net asp.net-mvc azure imagemagick


    【解决方案1】:

    我有这个例程为我工作

    public Bitmap FitImage(Image imgPhoto, int Width, int Height)
    {
      int sourceWidth = imgPhoto.Width;
      int sourceHeight = imgPhoto.Height;
      int sourceX = 0;
      int sourceY = 0;
      int destX = 0;
      int destY = 0;
    
      float nPercent = 0;
      float nPercentW = 0;
      float nPercentH = 0;
    
      nPercentW = ((float)Width / (float)sourceWidth);
      nPercentH = ((float)Height / (float)sourceHeight);
    
      if (nPercentH < nPercentW) {
        nPercent = nPercentW;
        destY = (int)((Height - (sourceHeight * nPercent)) / 2);
      } else {
        nPercent = nPercentH;
        destX = (int)((Width - (sourceWidth * nPercent)) / 2);
      }
    
      int destWidth = (int)Math.Round(sourceWidth * nPercent);
      int destHeight = (int)Math.Round(sourceHeight * nPercent);
    
      Bitmap newPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
      Graphics newgrPhoto = Graphics.FromImage(newPhoto);
      newgrPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; 
      newPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
    
      newgrPhoto.PixelOffsetMode = PixelOffsetMode.Half;
    
      var attr = new ImageAttributes();
      attr.SetWrapMode(WrapMode.TileFlipXY);
    
      newgrPhoto.DrawImage(imgPhoto,
          new Rectangle(destX, destY, destWidth, destHeight),
          sourceX, sourceY, sourceWidth, sourceHeight,
          GraphicsUnit.Pixel,
          attr
       );
    
      newgrPhoto.Dispose();
    
      return newPhoto;
    }
    

    可能不会完全按照您的意愿行事,但您会大致了解。它在多线程环境中使用,不会泄漏。

    【讨论】:

    • 谢谢,这就是我已经在使用的。但是,我相信在服务器环境中使用 GDI 是有警告的。此外,调整大小发生在单个线程上,因此不适用于较大的图像。
    • 哎呀抱歉没有意识到。我要删除这个答案吗?不知道这里通常是什么:-)
    猜你喜欢
    • 2016-08-18
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    相关资源
    最近更新 更多