WPF – converting Bitmap to ImageSource

For others, this works: //If you get ‘dllimport unknown’-, then add ‘using System.Runtime.InteropServices;’ [DllImport(“gdi32.dll”, EntryPoint = “DeleteObject”)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DeleteObject([In] IntPtr hObject); public ImageSource ImageSourceFromBitmap(Bitmap bmp) { var handle = bmp.GetHbitmap(); try { return Imaging.CreateBitmapSourceFromHBitmap(handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } finally { DeleteObject(handle); } }

BitmapImage to byte[]

To convert to a byte[] you can use a MemoryStream: byte[] data; JpegBitmapEncoder encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapImage)); using(MemoryStream ms = new MemoryStream()) { encoder.Save(ms); data = ms.ToArray(); } Instead of the JpegBitmapEncoder you can use whatever BitmapEncoder you like as casperOne said. If you are using MS SQL you could also use a image-Column … Read more

Embedding resources (images, sound bits, etc) into a Java project then use those resources

Just put those resources in the source/package structure and use ClassLoader#getResource() or getResourceAsStream() to obtain them as URL or InputStream from the classpath by the full qualified package path. ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream input = classLoader.getResourceAsStream(“/image.gif”); // … Or if it is in the same package as the current class, you can also obtain … Read more

How do I change an image source dynamically from code-behind in WPF with an image in Properties.Resources?

Although an image resource in a WPF project generates a System.Drawing.Bitmap property in Resources.Designer.cs, you could directly create a BitmapImage from that resource. You only need to set the Build Action of the image file to Resource (instead of the default None). If you have a file Red.jpg in the Resources folder of your Visual … Read more