-
Notifications
You must be signed in to change notification settings - Fork 239
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a349551
commit 4139ff4
Showing
3 changed files
with
62 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
using System; | ||
using System.Drawing; | ||
using System.Drawing.Imaging; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Windows; | ||
using System.Windows.Media.Imaging; | ||
using System.Windows.Threading; | ||
|
||
namespace WPFDevelopers | ||
{ | ||
public static class ImagingHelper | ||
{ | ||
public static BitmapSource CreateBitmapSourceFromBitmap(Bitmap bitmap) | ||
{ | ||
if (bitmap == null) | ||
throw new ArgumentNullException("bitmap"); | ||
|
||
if (Application.Current.Dispatcher == null) | ||
return null; | ||
try | ||
{ | ||
using (MemoryStream memoryStream = new MemoryStream()) | ||
{ | ||
bitmap.Save(memoryStream, ImageFormat.Png); | ||
memoryStream.Seek(0, SeekOrigin.Begin); | ||
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) | ||
{ | ||
var bitmapDecoder = BitmapDecoder.Create( | ||
stream, | ||
BitmapCreateOptions.PreservePixelFormat, | ||
BitmapCacheOption.OnLoad); | ||
|
||
var writable = new WriteableBitmap(bitmapDecoder.Frames.Single()); | ||
writable.Freeze(); | ||
return writable; | ||
} | ||
} | ||
} |
Binary file not shown.