|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ImageSourceExtensions.cs" company="Catel development team">
// Copyright (c) 2008 - 2011 Catel development team. All rights reserved.
// </copyright>
// <summary>
// Extensions for the <see cref="ImageSource" /> class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Catel.Windows.Media
{
/// <summary>
/// Extensions for the <see cref="ImageSource"/> class.
/// </summary>
public static class ImageSourceExtensions
{
/// <summary>
/// Converts an array of bytes to a <see cref="ImageSource"/>.
/// </summary>
/// <param name="bytes">Bytes to convert.</param>
/// <returns><see cref="ImageSource"/>.</returns>
public static ImageSource ConvertByteArrayToImageSource(this byte[] bytes)
{
if (bytes.Length == 0)
{
return null;
}
ImageSource result;
// Create memory stream - it seems that if you clean up or dispose
// the memory stream, you cannot display the image any longer
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DecodePixelWidth = 600;
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
result = bitmapImage;
}
return result;
}
/// <summary>
/// Converts an <see cref="ImageSource"/> to an array of bytes.
/// </summary>
/// <param name="image"><see creConvertImageSourceToByteArrayf="ImageSource"/> to convert.</param>
/// <returns>Array of bytes.</returns>
public static byte[] ConvertImageSourceToByteArray(this ImageSource image)
{
byte[] result;
BitmapFrame bitmapFrame = null;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
BitmapSource bitmapSource = null;
bitmapSource = (BitmapSource)image;
bitmapFrame = BitmapFrame.Create(bitmapSource);
encoder.Frames.Add(bitmapFrame);
using (MemoryStream memoryStream = new MemoryStream())
{
encoder.Save(memoryStream);
result = memoryStream.ToArray();
encoder.Frames.Clear();
}
// Force garbage collection to prevent lots of memory usage
GC.WaitForPendingFinalizers();
GC.Collect();
return result;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.