2015-12-11 21 views
0

我需要你的幫助。我想編寫像PhotoShop這樣的函數。如何正確轉換WPF中的圖像?

1.upload圖像

enter image description here 2.然後我想要做的歪斜變換,但是當我做變換我有一個問題,我的照片超出了工作區的邊緣。 enter image description here 如何在沒有此問題的情況下進行轉換(我認爲每次進行轉換時都應該創建一個新的圖像)。

然後我裁剪,但裁剪使圖片沒有變形。我認爲,如果每次進行轉換時都創建一個新圖像,問題將得到解決。

如何做到這一點是否正確?

如何在WPF中正確創建此圖像?如何進行變換並保存圖像?我正在使用(System.Drawing.Bitmap,System.Windows.Media.Imaging)也許,有人可以顯示我的經驗,代碼或有用的材料?

Thenk you so much。

回答

2

對於偏斜變形,您可以使用MatrixTranform。基本的想法進行說明here

下面是變換位於圖像的代碼「d:\ input.png」,高度變換結果是,在的.xaml文件定義的圖像的來源:

<Image Name="imgProcess" /> 

並寫入結果到文件 「d:\ skew.png」

 double skewX = .0; 
     double skewY = Math.Tan(Math.PI/18); 
     MatrixTransform transformation = new MatrixTransform(1, skewY, skewX, 1, 0, 0) 

     BitmapImage image = new BitmapImage(new Uri(@"D:\input.png")); 
     var boundingRect = new Rect(0, 0, image.Width + image.Height * skewX, image.Height + image.Width * skewY); 
     DrawingGroup dGroup = new DrawingGroup(); 
     using (DrawingContext dc = dGroup.Open()) 
     { 
      dc.PushTransform(transformation); 

      dc.DrawImage(image, boundingRect); 
     } 


     DrawingImage imageSource = new DrawingImage(dGroup); 


     imgProcess.Source = imageSource; 

     SaveDrawingToFile(ToBitmapSource(imageSource), @"D:\skew.png", (int)boundingRect.Width, (int)boundingRect.Height); 

    private BitmapSource ToBitmapSource(DrawingImage source) 
    { 
     DrawingVisual drawingVisual = new DrawingVisual(); 
     DrawingContext drawingContext = drawingVisual.RenderOpen(); 
     drawingContext.DrawImage(source, new Rect(new Point(0, 0), new Size(source.Width, source.Height))); 
     drawingContext.Close(); 

     RenderTargetBitmap bmp = new RenderTargetBitmap((int)source.Width, (int)source.Height, 96, 96, PixelFormats.Pbgra32); 
     bmp.Render(drawingVisual); 
     return bmp; 
    } 


    private void SaveDrawingToFile(BitmapSource image, string fileName, int width, int height) 
    { 
     var encoder = new PngBitmapEncoder(); 
     encoder.Frames.Add(BitmapFrame.Create(image)); 

     using (var stream = new FileStream(fileName, FileMode.Create)) 
     { 
      encoder.Save(stream); 
     } 
    } 

Results