2013-11-20 121 views
0

問題說明了一切。我看了很多例子,並且搜索了很多,但似乎沒有任何工作。將System.windows.Controls.Image轉換爲System.Drawing.Bitmap

這是我的代碼:

System.Windows.Controls.Image abc = Image; 
// SaveImageToJPEG(abc, "C:/1.jpg"); 

FindShape(new System.Drawing.Bitmap((Image.Source as BitmapImage).StreamSource)); 

行:(Image.Source as BitmapImage)回報null

那麼,如何從System.windows.controls.Image獲取位圖?

這個問題是非常不同於所有的那些..我嘗試了一切,它並沒有爲我工作。但最後我找到了解決方案。不幸的是,我不能將它作爲答案發布,因爲這裏的人在stackoverflow非常渴望關閉它。 無論如何..有這個答案:

System.Windows.Controls.Image abc = Image;

  MemoryStream ms = null; 
      JpegBitmapEncoder jpegBitmapEncoder = null; 
      BitmapEncoder bencoder = new JpegBitmapEncoder(); 

      System.Drawing.Bitmap bmp = null; 
      BitmapImage bitmapImage = new BitmapImage(); 

      if ((int)abc.Source.Width>0) 
      { 
       RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)abc.Source.Width, 
                       (int)abc.Source.Height, 
                       100, 100, PixelFormats.Default); 
       renderTargetBitmap.Render(abc); 

       jpegBitmapEncoder = new JpegBitmapEncoder(); 
       //jpegBitmapEncoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); 
       bencoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap)); 
       using (ms = new MemoryStream()) 
       { 

        bencoder.Save(ms); 

        //if (ms != null) 
        { 
         bmp = new System.Drawing.Bitmap(ms); 
         //bmp.Save("C:/bmp_thing.jpg"); 

         if (bmp != null) 
         { 

          count++; 
          if(count ==60){ 
          int shape_type =FindShape(bmp); 
          Tetris_Game.NextBlockType = shape_type; 


          count = 0; 
          } 
          // open_img.Dispose(); 

         } 
         bmp.Dispose(); 
         //ms.Flush(); 

        } 

       } 

      } 
+0

但是,該鏈接是爲BitmapSource。如何將圖像源轉換爲位圖源? 。我試過(Image.Source爲BitmapSource)我得到一個錯誤 – Nikhil

+0

Source需要從一開始就是一個BitmapImage以供您檢索它。你是否將Uri設置爲Image.Source,並期望在它下載後獲得BitmapImage? – atomaras

+0

我從KinectDevice獲取圖像...即從相機。我不知道它是什麼格式。我所知道的是,來自相機的圖像被分配給'System.Windows.Controls.Image'。 – Nikhil

回答

0

WriteableBitmap旋轉並嘗試渲染您的Image元素。之後,通過複製像素來創建System.Drawing.Bitmap,因爲WriteableBitmap爲您提供原始的訪問權限。

在創建了WriteableBitmap後,請查看here瞭解如何將其轉換爲位圖。

+0

如何初始化WritableBitmap?我從哪裏獲得BitmapSource? – Nikhil

+0

WriteableBitmap沒有渲染方法 – Nikhil

+0

WriteableBitmap是一個BitmapSource。你的.NET版本是什麼?應該有一個構造函數或方法接受UIElement。 – atomaras

相關問題