public static System.Windows.Controls.Image ByteArrayToImage(byte[] bytesImg) { System.Windows.Media.Imaging.BitmapImage bitmapImage = new System.Windows.Media.Imaging.BitmapImage(); bitmapImage.BeginInit(); bitmapImage.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad; bitmapImage.StreamSource = new MemoryStream(bytesImg); bitmapImage.EndInit(); System.Windows.Controls.Image img = new System.Windows.Controls.Image(); img.Source = bitmapImage; return img; }
Image To Byte[]
public static byte[] BitmapImageToByteArray(System.Windows.Controls.Image img) { byte[] ImgTemp; System.Windows.Media.Imaging.BitmapImage bitmapImage = new System.Windows.Media.Imaging.BitmapImage(); bitmapImage = ((System.Windows.Media.Imaging.BitmapImage)img.Source); System.Windows.Media.Imaging.JpegBitmapEncoder encoder = new System.Windows.Media.Imaging.JpegBitmapEncoder(); encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmapImage)); using (MemoryStream ms = new MemoryStream()) { encoder.Save(ms); ImgTemp = ms.ToArray(); } return ImgTemp; }
test code
Test snippet code
private ContextMenuStrip menuPanelTastoDx() { ContextMenuStrip contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(); ToolStripMenuItem item; item = new ToolStripMenuItem(); item.Text = "Cancella Immagine"; item.ImageIndex = 0; contextMenuStrip1.Items.Add(item); item = new ToolStripMenuItem(); item.Text = "Dettagli"; item.ImageIndex = 1; contextMenuStrip1.Items.Add(item); contextMenuStrip1.Items.Add(new ToolStripSeparator()); item = new ToolStripMenuItem(); item.Text = "Cancella tutte le descrizioni"; item.ImageIndex = 2; contextMenuStrip1.Items.Add(item); contextMenuStrip1.ItemClicked += contextMenuStrip1_ItemClicked; return contextMenuStrip1; }