wpf - Can i use System.Drawing in wpf?

余生长醉 提交于 2019-11-28 08:12:23

问题


i am saving the image in database. .. but how to retrieve that image from database .. when i try to use system.drawing .. it shows an error .. some of ppl saying i can't use system.drwaing in wpf .. not even dll file ..

my code is

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;
    }

what to do now?

i used the system.drawing.dll .. now i can use system.drawing.bitmap .. but after using it shows an error at System.Drawing.Image.FromStream(strm);

error:- argument exception was unhandled by user code

Parameter is not valid.


回答1:


You can use the classes in the System.Drawing namespace, but you will have to add a reference to the assembly containing the class you're interested in, by right clicking on the project, and choosing the "Add Reference..." option




回答2:


Your code is fine as far as the drawing part is concerned, the problem is probably with the image data you are trying to load from the database (might be caused by mismatched data format or choosing the wrong column etc.). You might want to share the code that saves the image to the database, since there is no way to know without it.

This code sample does what you want (I commented out the database related part and substituted it with file loading):

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;
}

With that said, if this is a new application, using WPF solely is preferable to mixing Windows Forms and WPF classes and elements (as Jeff Mercado pointed out).



来源:https://stackoverflow.com/questions/10663056/wpf-can-i-use-system-drawing-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!