Skip to content

Instantly share code, notes, and snippets.

@JohanLarsson
Created July 18, 2013 15:48
Show Gist options
  • Save JohanLarsson/6030437 to your computer and use it in GitHub Desktop.
Save JohanLarsson/6030437 to your computer and use it in GitHub Desktop.
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Conceal;
namespace ConcealView
{
public static class BitMapExt
{
/// <summary>
/// http://www.codeproject.com/Articles/104929/Bitmap-to-BitmapSource
/// </summary>
/// <param name="bitmap"></param>
/// <returns></returns>
public static BitmapSource ToBitmapSource(this Bitmap bitmap)
{
if (bitmap == null)
throw new ArgumentNullException("bitmap");
if (Application.Current.Dispatcher == null)
return null; // Is it possible?
try
{
using (var memoryStream = new MemoryStream())
{
// You need to specify the image format to fill the stream.
// I'm assuming it is PNG
bitmap.Save(memoryStream, ImageFormat.Png);
memoryStream.Seek(0, SeekOrigin.Begin);
// Make sure to create the bitmap in the UI thread
if (InvokeRequired)
return (BitmapSource)Application.Current.Dispatcher.Invoke(
new Func<Stream, BitmapSource>(CreateBitmapSourceFromBitmap),
DispatcherPriority.Normal,
memoryStream);
return CreateBitmapSourceFromBitmap(memoryStream);
}
}
catch (Exception)
{
return null;
}
}
private static bool InvokeRequired
{
get { return Dispatcher.CurrentDispatcher != Application.Current.Dispatcher; }
}
private static BitmapSource CreateBitmapSourceFromBitmap(Stream stream)
{
BitmapDecoder bitmapDecoder = BitmapDecoder.Create(
stream,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.OnLoad);
// This will disconnect the stream from the image completely...
WriteableBitmap writable = new WriteableBitmap(bitmapDecoder.Frames.Single());
writable.Freeze();
return writable;
}
public static async Task<Bitmap> LoadBitmap(string imagePath, bool throwOnException)
{
Bitmap bitmap = null;
if (!string.IsNullOrWhiteSpace(imagePath))
{
try
{
if (File.Exists(imagePath))
{
bitmap = await Task<Bitmap>.Factory.StartNew(() => (Bitmap)Image.FromStream(File.OpenRead(imagePath)));
}
else if (Uri.IsWellFormedUriString(imagePath, UriKind.RelativeOrAbsolute))
{
using (Stream stream = await new WebClient().OpenReadTaskAsync(imagePath))
{
bitmap = (Bitmap)Image.FromStream(stream);
}
}
}
catch (Exception)
{
if (throwOnException)
{
throw;
}
}
}
return bitmap;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment