推荐的快速、安全的服务器端图像调整方法

本文关键字:服务器端 图像 调整 安全 方法 | 更新日期: 2023-09-27 18:03:58

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

我担心的是,这应该不泄漏内存,应该是线程安全的,多线程的,应该提供高质量的结果。ImageMagick似乎提供了所有这些。然而,System.Windows.Media.Imaging被认为是一种"更清洁"的解决方案。

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

还有其他我应该考虑的选择吗?

推荐的快速、安全的服务器端图像调整方法

我有这个例程为我工作

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;
}

可能不完全是你想要的,但你会得到一般的想法。它在多线程环境中使用,不会泄漏。