2012-11-12 146 views
0

我遇到了一些使用WPF調整圖像大小的問題,因爲圖像在某些分辨率下出現模糊。我實際上是把這些文件寫出來,所以SnapToDevicePixels不會幫助(我甚至沒有在WPF應用程序中,我只是參考System.Windows)。我知道這與WPF中像素的設備無關性有關,但我現在需要知道如何計算像素的偏移量,以便獲得清晰的圖像。公式來確定wpf調整圖像的正確偏移量

回答

0

是否有任何需要使用WPF?我們使用這種GDI基於代碼產生極好的大小調整的權力:

public static Size ResizeImage(
     string fileName, 
     string targetFileName, 
     Size boundingSize, 
     string targetMimeType, 
     long quality) 
    { 
     ImageCodecInfo imageCodecInfo = 
      ImageCodecInfo 
       .GetImageEncoders() 
       .Single(i => i.MimeType == targetMimeType); 
     EncoderParameters encoderParams = new EncoderParameters(1); 
     encoderParams.Param[0] = 
      new EncoderParameter(Encoder.Quality, quality); 
     using (FileStream fs = File.OpenRead(fileName)) 
     { 
      Image img ; 
      try 
      { 
       img = Image.FromStream(fs, true, true); 
      } 
      catch (ArgumentException ex) 
      { 
       throw new FileFormatException("cannot decode image",ex); 
      } 
      using (img) 
      { 
       double targetAspectRatio = 
        ((double)boundingSize.Width)/boundingSize.Height; 
       double srcAspectRatio = ((double)img.Width)/img.Height; 
       int targetWidth = boundingSize.Width; 
       int targetHeight = boundingSize.Height; 
       if (srcAspectRatio > targetAspectRatio) 
       { 
        double h = targetWidth/srcAspectRatio; 
        targetHeight = Convert.ToInt32(Math.Round(h)); 
       } 
       else 
       { 
        double w = targetHeight * srcAspectRatio; 
        targetWidth = Convert.ToInt32(Math.Round(w)); 
       } 
       using (Image thumbNail = new Bitmap(targetWidth, targetHeight)) 
       using (Graphics g = Graphics.FromImage(thumbNail)) 
       { 
        g.CompositingQuality = CompositingQuality.HighQuality; 
        g.SmoothingMode = SmoothingMode.HighQuality; 
        g.InterpolationMode = InterpolationMode.HighQualityBicubic; 
        g.PixelOffsetMode = PixelOffsetMode.HighQuality; 
        Rectangle rect = 
         new Rectangle(0, 0, targetWidth, targetHeight); 
        g.DrawImage(img, rect); 
        thumbNail.Save(
         targetFileName, imageCodecInfo, encoderParams); 
       } 
       return new Size(targetWidth, targetHeight); 
      } 

     } 
    } 
+0

GDI是備用的,但我們遇到這需要鎖定獲取在過去四周,並根據包裝盒上,WPF標籤的很多問題對於這種事情應該會更快。我們已經使用WPF一段時間了,並且已經解決了大部分我們將會看到的大問題。這可能聽起來像沉沒的成本,但這似乎是一個小問題,我希望它是一個簡單的孤立解決方案,這意味着我不必重寫現有解決方案的大部分。 – Khanzor