2

我一直在 Asp.Net hadler 中使用 GDI+ 实现来调整图像大小。我发现文章Resizing images from the server using WPF/WIC instead of GDI+描述了使用 Windows.Media.Imaging 调整图像大小更有效(更快并且消耗更少的系统资源)。

这种方法还有一个优势,我可以从源图像中读取单个帧,例如 gif。这是我的代码的一部分:

var photoDecoder = BitmapDecoder.Create(inputStream, BitmapCreateOptions.PreservePixelFormat,
                                                BitmapCacheOption.None);
IEnumerable<BitmapFrame> bitmapFrames = from bitmapFrame in photoDecoder.Frames
                                                select bitmapFrame;

var bitmapFramesList = new List<BitmapFrame>();
bitmapFramesList.AddRange(bitmapFrames);

var firstFrame = bitmapFramesList.First();

int inputWidth = Convert.ToInt32(firstFrame.Width);
int inputHeight = Convert.ToInt32(firstFrame.Height);

var firstFrameSize= new Size(inputWidth, inputHeight);

//if targetSize is bigger than image Size render image as is
bool targetSizeIsBiggerOrEmpty = targetSize.IsEmpty || (targetSize.Width > firstFrameSize.Width && targetSize.Height > firstFrameSize.Height);   
if (targetSizeIsBiggerOrEmpty)
{
   inputStream.Position = ZERO;
   inputStream.CopyTo(catalogImage.Stream);
}
else
{
   //calculate size of target image
   Size imageSize = SizeCalculator.CalculateImageSize(new Size(Convert.ToInt32(firstFrame.Width),Convert.ToInt32(firstFrame.Height)), targetSize);
   if (targetSize.Width == ZERO)
      targetSize.Width = imageSize.Width;
   if (targetSize.Height == ZERO)
      targetSize.Height = imageSize.Height;

   double scaleX = Convert.ToDouble(imageSize.Width) / Convert.ToDouble(firstFrame.Width);
   double scaleY = Convert.ToDouble(imageSize.Height) / Convert.ToDouble(firstFrame.Height);
   double scale = Math.Min(scaleX, scaleY);

   var targetFrames= new Collection<BitmapFrame>();
   foreach (var sourceFrame in bitmapFramesList)
   {                    
      var transform = new ScaleTransform {ScaleX = scale, ScaleY = scale};
      var transformedBitmap = new TransformedBitmap(sourceFrame, transform);
      BitmapFrame bitmapFrame = BitmapFrame.Create(transformedBitmap);
      targetFrames.Add(bitmapFrame);
   }

   //my own method for saving image to response output stream
   SaveCatalogImage(catalogImage, targetFrames);

}

但这里有个小问题。每个帧都有不同的大小,我无法根据第一帧大小找到每个帧的位置。我还需要在源图像中对目标图像进行计时

我在哪里可以在源图像中找到这些信息?

4

0 回答 0