Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Media.Imaging;
namespace LightSwitchApplication.Helpers
{
public class ImageHelper
{
public static BitmapImage GetEmbeddedResourceBitmapImage(byte[] bytes)
{
// Create a BitmapImage from a byte[];
using (MemoryStream ms = new MemoryStream(bytes))
{
var bi = new BitmapImage();
bi.SetSource(ms);
return bi;
}
}
public static byte[] GetEmbeddedResourceImageByName(string name)
{
try
{
// Παίρνουμε τα meta-info της τρέχουσας assembly
var assemply = Assembly.GetExecutingAssembly();
var names = assemply.GetManifestResourceNames();
// Βρισκουμε το embedded resource της τρεχουσας assembly assembly αν υπάρχει στην λίστα
var fullQualifiedName = names.FirstOrDefault(r => r.Contains(name));
if (string.IsNullOrWhiteSpace(fullQualifiedName)) return null;
// Παίρνουμε το stream του πόρου και το επιστρέφουμε για να δείξει static image
var stream = assemply.GetManifestResourceStream(fullQualifiedName);
return GetStreamAsByteArray(stream);
}
catch (Exception)
{
return null;
}
}
private static byte[] GetStreamAsByteArray(Stream stream)
{
try
{
var streamLength = Convert.ToInt32(stream.Length);
var buffer = new byte[streamLength];
stream.Read(buffer, 0, streamLength);
return buffer;
}
finally
{
stream.Close();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment