簡體   English   中英

wpf - 我可以在wpf中使用System.Drawing嗎?

[英]wpf - Can i use System.Drawing in wpf?

我將圖像保存在數據庫中。 ..但如何從數據庫中檢索該圖像..當我嘗試使用system.drawing ..它顯示一個錯誤..一些ppl說我不能在wpf中使用system.drwa ..甚至不是dll文件..

我的代碼是

private void btnShow_Click(object sender, RoutedEventArgs e)
{
       DataTable dt2 =  reqBll.SelectImage().Tables[0];
       byte[] data = (byte[])dt2.Rows[0][1];
       MemoryStream strm = new MemoryStream();
       strm.Write(data, 0, data.Length);
       strm.Position = 0;
       System.Drawing.Image img = System.Drawing.Image.FromStream(strm);
       BitmapImage bi = new BitmapImage();
       bi.BeginInit();
       MemoryStream ms = new MemoryStream();
       img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
       ms.Seek(0, SeekOrigin.Begin);
       bi.StreamSource = ms;
       bi.EndInit();
       ImgBox.Source = bi;
    }

現在做什么?

我使用了system.drawing.dll ..現在我可以使用system.drawing.bitmap ..但是在使用它之后在System.Drawing.Image.FromStream(strm)中顯示錯誤;

錯誤: - 用戶代碼未處理參數異常

參數無效。

可以使用System.Drawing命名空間中的類,但是您必須通過右鍵單擊項目並選擇“Add Reference ...”選項來添加對包含您感興趣的類的程序集的引用。

就繪圖部分而言,您的代碼很好,問題可能在於您嘗試從數據庫加載的圖像數據(可能是由不匹配的數據格式或選擇錯誤的列等引起的)。 您可能希望共享將圖像保存到數據庫的代碼,因為沒有它就無法知道。

此代碼示例執行您想要的操作(我注釋掉了數據庫相關部分並將其替換為文件加載):

private void btnShow_Click(object sender, RoutedEventArgs e)
{
  // DataTable dt2 = reqBll.SelectImage().Tables[0];
  // byte[] data = (byte[]) dt2.Rows[0][1];
  // MemoryStream strm = new MemoryStream();
  // strm.Write(data, 0, data.Length);

  System.Drawing.Image bmp = System.Drawing.Bitmap.FromFile(@"C:\Temp\test.png");
  MemoryStream strm = new MemoryStream();
  bmp.Save(strm, System.Drawing.Imaging.ImageFormat.Bmp);

  strm.Position = 0;
  System.Drawing.Image img = System.Drawing.Image.FromStream(strm);
  BitmapImage bi = new BitmapImage();
  bi.BeginInit();
  MemoryStream ms = new MemoryStream();
  img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

  ms.Seek(0, SeekOrigin.Begin);
  bi.StreamSource = ms;
  bi.EndInit();
  imgBox.Source = bi;
}

話雖如此,如果這是一個新的應用程序,單獨使用WPF比混合Windows窗體和WPF類和元素更好(正如Jeff Mercado指出的那樣)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM