2017-10-13 162 views
0

我試圖將裁切後的圖像(和/或網格)轉換爲新的普通圖像,但是在裁剪後,它會在相同位置返回,如何修復,我的工作方式裁剪通過裁剪獲取新圖像

enter image description here

private async void Save(object sender, RoutedEventArgs e) 
     { 
      RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); 
      await renderTargetBitmap.RenderAsync(GGrid, 4096 , 2448); 
      // IBuffer pixels = await renderTargetBitmap.GetPixelsAsync(); 
      IBuffer pixelBuffer = await renderTargetBitmap.GetPixelsAsync(); 
      FileSavePicker fileSavePicker = new FileSavePicker(); 
      fileSavePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; 
      fileSavePicker.FileTypeChoices.Add("JPEG files", new List<string>() { ".png"}); 
      fileSavePicker.SuggestedFileName = "image"; 

      var outputFile = await fileSavePicker.PickSaveFileAsync(); 

      if (outputFile == null) 
      { 
       // The user cancelled the picking operation 
       return; 
      } 
      using (IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite)) 
      { 

       var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream); 
       encoder.SetPixelData(
        BitmapPixelFormat.Bgra8, 
        BitmapAlphaMode.Straight, 
        (uint)renderTargetBitmap.PixelWidth, 
        (uint)renderTargetBitmap.PixelHeight, 
        DisplayInformation.GetForCurrentView().LogicalDpi, 
        DisplayInformation.GetForCurrentView().LogicalDpi, 
        pixelBuffer.ToArray()); 
       try 
       { 

        await encoder.FlushAsync(); 
       } 
       catch (Exception err) 
       { 
        switch (err.HResult) 
        { 
         case unchecked((int)0x88982F81): //WINCODEC_ERR_UNSUPPORTEDOPERATION 
                 // If the encoder does not support writing a thumbnail, then try again 
                 // but disable thumbnail generation. 
          encoder.IsThumbnailGenerated = false; 
          break; 
         default: 
          throw err; 
        } 
       } 

       //if (encoder.IsThumbnailGenerated == false) 
       //{ 
       // await encoder.FlushAsync(); 
       //} 


      } 
     } 
+0

'GGrid'的內容是什麼樣的?你可以發佈XAML和截圖嗎? – Laith

+0

我已經完成了它,謝謝,我只是更改XAML –

回答

0

enter image description here

程序後,您需要翻譯和作物的位圖。

double x,y,w,h; 

GGrid.RenderTransform = new TranslateTransform 
{ 
    X = -x, // translate back to origin (0,0) 
    Y = -y 
}; 

RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(); 
await renderTargetBitmap.RenderAsync(GGrid, w, h); // use crop size 
+0

感謝您的答覆,實際上它不會創建新的圖像它只是改變位置,仍然有空的位置 –

+0

當您使用較小的尺寸時會發生什麼? '等待renderTargetBitmap.RenderAsync(GGrid,400,300);'你看到更少的黑色空間了嗎? – Laith

+0

我看到更多的黑色空間,它只是使圖像更小 –