Get image from resource dll as MemoryStream - wpf

I use WPF and my program has images in a DLL resource file. I have this well working way to read in images from disk:
Private Function GetImageFromFile(ByVal fileName As String) As BitmapImage
Dim buffer As Byte() = IO.File.ReadAllBytes(fileName)
Dim memoryStream As New IO.MemoryStream(buffer)
Dim bitmap As New BitmapImage()
bitmap.BeginInit()
bitmap.StreamSource = memoryStream
bitmap.EndInit()
bitmap.Freeze()
Return bitmap
End Function
Now, how can I get images in this MemoryStream-way from a DLL resource?
The basic problem: If I use simply the "bitmap.UriSource = whatever uri" way and load many images in sequence like an animation it builds up the memory. I tried with the above memorystream way and it worked perfectly fine, but then I store my images in a dll and I don't know how to do this trick. If anybody knows how to read many images from a managed dll without building up the memory pls, let me know.

I found the answer to my question. I put it here for others who may need it. There are more ways to load images from a resource dll file. The easiest way to initialize the BitmapImage and set bi.UriSource=uriPath (where the path looks like I show below) but when you load images in a sequence, as an animation for example, it seems to take a lot of memory. Then you can use a StreamResourceInfo as shown below and just put like bi.StreamSource = sri.Stream. That works, too, but memorywise it has same results. So in practice I found the following way the fastest and most memory efficient way to load hundreds of images in a sequence:
Public Function GetImageFromDLL(ByVal uriPath As String) As BitmapImage
Dim sri As Windows.Resources.StreamResourceInfo = Application.GetResourceStream(New Uri(uriPath, UriKind.Absolute))
Dim binReader As New System.IO.BinaryReader(sri.Stream)
Dim buffer As Byte() = binReader.ReadBytes(sri.Stream.Length)
Dim memoryStream As New IO.MemoryStream(buffer)
Dim bi As New BitmapImage()
bi.BeginInit()
bi.CacheOption = BitmapCacheOption.Default
bi.CreateOptions = BitmapCreateOptions.None
bi.StreamSource = memoryStream
bi.EndInit()
bi.Freeze()
Return bi
End Function
Where the uriPath is something like: "pack://application:,,,/YourDLL;Component/YourImageFile.jpg"

Related

Deserializing byte to image from sql through memory stream

I have convert an image to be saved in SQL Server Database as Binary with column name as "img". I have PictureBox1 ready to show the image.
Now I want to import the binary data back into image, and I'm trying this code in VB.net for example:
Dim queries As String
queries = "SELECT * from StudentData where Std_fname='" & ComboBox1.Text & "'"
Dim com As New SqlCommand(queries, sqlconn)
sqlconn.Open()
Dim ds As New SqlDataAdapter(queries, sqlconn)
Dim dr As SqlDataReader
dr = com.ExecuteReader()
While dr.Read
Std_fnameTextBox.Text = dr("Std_fname")
Std_lnameTextBox.Text = dr("Std_lname")
AgeTextBox.Text = dr("age")
AddressTextBox.Text = dr("address")
StateTextBox.Text = dr("state")
CityTextBox.Text = dr("city")
CountryTextBox.Text = dr("country")
Ic_passportTextBox.Text = dr("ic_passport")
DobDateTimePicker.Text = dr("dob")
PictureBox1.Image = dr("img") 'Here is the problem. If I run it, it ask me to convert Binary to Image first.
End While
sqlconn.Close()
The problem is, I don't know how to convert binary to image in this situation. And yes, I've been googling for it, but can't seem to get the right answer.
dr("img") returns either DBNull.Value, or a byte[]. You can use the stream overload of the Bitmap constructor to load this. In C# (should be easy to translate to VB), you can do it like this:
var imageData = (byte[])dr["img"];
using (var ms = new MemoryStream(imageData))
{
var bmp = new Bitmap(ms);
// Work with bmp
}
As Mark correctly noted, you're supposed to keep the stream open for the whole life-time of the Bitmap - this is actually a bit trickier than it seems, because the Bitmap doesn't even keep a reference to the stream.
The easiest way to handle this is to clone the bitmap after you create it, to remove the dependency on the stream. Unless you can do whatever work you need to do within the using - unlikely if you want to display it in a PictureBox.
You can also use ImageConverter.ConvertFrom directly, but all it does is create the MemoryStream if used on raw byte[] data :)

Create a FrameworkElement out of an BitmapImage file, and then destroy?

I have a WPF project, which we using some WindowsForm control(PivotTable from OWC, Office Web Component). However, since the PivotTable doesn't support print very well, the only way we can think of is to print the image file PivotTable exports(another way is to print from exported Excel file, but we want to avoid it since it is not guaranteed that Excel is installed on the machine).
We already have one print project, which will print WPF ElementFramework nicely. So I want to use that piece of code. Now my question is: how I can generate a FrameworkElement out of a BitmapImage from code. Since this FrameworkElement is purely for printing, so I guess I must create it from the code, probably assign a parent to it, not show it on the screen, and after the printing destroy the FrameworkElement so that ultimately I can delete the temp BitmapImage file.
So this is beyond my knowledge. I don't even know whether that's a proper way: create a UI element for some non-UI related work? Any advice on that? Thanks!
You should load the temp image file's bytes into memory and create a Image from those bytes.
Your Image will not use the temp file directly and you can delete it immediately after reading the bytes, the rest is GarbageCollector's job. Here is a function to create your BitmapImage from bytes:
public static BitmapImage GetImageFromByteArray(byte[] rawImageBytes)
{
BitmapImage imageSource = null;
try
{
using (MemoryStream stream = new MemoryStream(rawImageBytes))
{
stream.Seek(0, SeekOrigin.Begin);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = stream;
bi.EndInit();
imageSource = bi;
}
}
catch (System.Exception)
{
}
return imageSource;
}
And use it like this:
testImage.Source = GetImageFromByteArray(rawImageBytes);

Create Ximage from (wpf) visual in memory

I'm trying to convert a visual to a Ximage(to print on pdf).
Currently I'm using this:
Dim img As XImage = XImage.FromFile(path.LocalPath)
But it requires me to save it on the harddrive
I would like to use this but I don't know how to create a image from a visual(in memory) and load it in.
Dim img As XImage = XImage.FromGdiPlusImage(myVisualAsImage)
If you use the WPF build of PDFsharp, you can also use:
public static XImage FromBitmapSource(BitmapSource image)
Several classes (including BitmapImage and WriteableBitmap) are derived from BitmapSource and can also be passed here.
See also:
http://ryancdavidson.com/blog/2009/09/getting-and-using-the-pixels-of-your-visual-in-wpf/
vb.net - overcome missing method FromGdiPlusImage in PDFSharp 1.5
Function getTiffImage(sourceImage As Image, pageNumber As Integer) As XImage
Dim ms As MemoryStream
Dim returnImage As XImage
Try
ms = New MemoryStream()
Dim objGuid As Guid = sourceImage.FrameDimensionsList(0)
Dim objDimension As Imaging.FrameDimension = New Imaging.FrameDimension(objGuid)
sourceImage.SelectActiveFrame(objDimension, pageNumber)
sourceImage.Save(ms, Imaging.ImageFormat.Tiff)
returnImage = XImage.FromStream(ms)
Catch ex As Exception
returnImage = Nothing
End Try
Return returnImage

WPF Write/Read BitmapImage to XML failing with 'No imaging component.....' Error

I am trying to write/read a BitmapImage to Xml using the XmlReader/XmlWriter classes. On writing out I can see a nice long CDATA section in the output Xml file. When reading in I can see that it is indeed reading in that same CDATA section data. But the attempt to recreate the BitmapImage is failing with the error...
"No imaging component suitable to complete this operation was found."
...on the line that says 'image.StreamSource = stream' below...
Public Sub WriteXmlImage(ByVal writer As XmlWriter, ByVal image as BitmapImage)
Using stream As New MemoryStream
Dim encoder = New PngBitmapEncoder
encoder.Frames.Add(BitmapFrame.Create(image))
encoder.Save(stream)
writer.WriteCData(Convert.ToBase64String(stream.ToArray()))
End Using
End Sub
Public Function ReadXmlImage(ByVal reader As XmlReader) As BitmapImage
Using stream As New IO.MemoryStream(Convert.FromBase64String(reader.Value))
Dim image As New BitmapImage
image.BeginInit()
image.StreamSource = stream
image.EndInit()
return image
End Using
End Sub
In testing I use the following trivial code to create a test BitmapImage...
Dim image As New BitmapImage(New Uri("c:\devil.png"))
Any ideas?

Is there a way to display a image in WPF stored in memory?

What I got is something like a screenshot making application. (managed to serialize, thank god!!!) When a button is clicked a screenshot is taken by accessing a handling classe's method. now the tricky part is that the class has another method for operating with the above said result, in such a manner than when the respective handling method is called, a window is created(shown) and the bitmap image should go into a display container in that window. The problem is that so far, I've noticed that in WPF the image control's source cannot be attribuited to a variable which stores the image. How can i display the image stored in that variable without having to save it first,get uri,etc. ?
You need to create an image from a memory stream, this has been well documented by many people. Here are two links that may get you started:
http://forums.silverlight.net/forums/p/44637/166282.aspx
http://www.wpftutorial.net/Images.html
thanks for the links slugster. Here's how I did it:
MemoryStream ms = new MemoryStream();
sBmp = gBmp; //note: gBmp is a variable that stores the captured image and passes it on to the method that uses sBMP as a distribuitor of the variable holding the captured image data
//variable that holds image
sBmp.Save(ms,ImageFormat.Bmp);
//my buffer byte
byte[] buffer = ms.GetBuffer();
//Create new MemoryStream that has the contents of buffer
MemoryStream bufferPasser = new MemoryStream(buffer);
//Creates a window with parents classthatholdsthismethod and null
Edit childEdit = new Edit(this, null);
childEdit.Show();
//I create a new BitmapImage to work with
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = bufferPasser;
bitmap.EndInit();
//I set the source of the image control type as the new BitmapImage created earlier.
childEdit.imgImageCanvas.Source = bitmap;
childEdit.Activate();
I've basically combined what I had found on those pages with some info I found on how to pass on a bmp to a memstream. I got this to work 100% :)

Resources