BitmapImage from file PixelFormat is always bgr32 - wpf

I am loading an image from file with this code:
BitmapImage BitmapImg = null;
BitmapImg = new BitmapImage();
BitmapImg.BeginInit();
BitmapImg.UriSource = new Uri(imagePath);
BitmapImg.CacheOption = BitmapCacheOption.OnLoad;
BitmapImg.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
BitmapImg.EndInit();
It works as expected except for the fact that no matter what kind of image I'm loading (24bit RGB, 8bit grey, 12bit grey,...), after .EndInit() the BitmapImage always has as Format bgr32. I know there have been discussions on the net, but I have not found any solution for this problem.
Does anyone of you know if it has been solved yet?
Thanks,
tabina

From the Remarks section in BitmapCreateOptions:
If PreservePixelFormat is not selected, the PixelFormat of the image
is chosen by the system depending on what the system determines will
yield the best performance. Enabling this option preserves the file
format but may result in lesser performance.
Therefore you also need to set the PreservePixelFormat flag:
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(imagePath);
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.CreateOptions = BitmapCreateOptions.IgnoreImageCache
| BitmapCreateOptions.PreservePixelFormat;
bitmap.EndInit();

For some reason I don't understand, using BitmapCreateOptions.PreservePixelFormat with new BitmapImage() didn't work for me. But this did lead me onto the right track. If anyone else tries the other answer and it doesn't work, this alternate method is what worked for me:
var decoder = new PngBitmapDecoder(new Uri(imagePath), BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapFrame frame = decoder.Frames[0];
For whatever reason PngBitmapDecoder worked where BitmapImage didn't.
Note: BitmapFrame inherits BitmapSource just like BitmapImage, for my purpose that was all I needed.

Related

WPF what is the best way to cache an image data

I have an application where I get lot of images in the form of byte[],
I store them in the memory for later use by the user demand
Should I store them in byte[]? or there is another way to store them for quicker loading on user demand?
My code that loads the image is like this
private static BitmapImage LoadImage(byte[] imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
Thank you!
Ron
Could store the images in a Dictionary.
The key is the unique identifier (E.G. Int32).
The image could be stored as byte[] or BitmapImage
If you store it as BitmapImage you have to convert the byte[] up front
But then you don't need to convert on demand
Dictionary<Int32, byte[]>
or
Dictionary<Int32, BitmapImage>
Pretty sure BitmapImage is going to be bigger so converting on demand would use less memory.
Your question said a lot of images but you also asked for quicker user loading.
Test both ways.

Create thumbnail image directly from header-less image byte array

My application shows a large number of image thumbnails at once. Currently, I am keeping all full size images in memory, and simply scaling the image in the UI to create the thumbnail. However, I'd rather just keep small thumbnails in memory, and only load the fullsize images when necessary.
I thought this would be easy enough, but the thumbnails I'm generating are terribly blurry compared to just scaling the fullsize image in the UI.
The images are byte arrays with no header information. I know the size and format ahead of time, so I can use BitmapSource.Create to create an ImageSource.
//This image source, when bound to the UI and scaled down creates a nice looking thumbnail
var imageSource = BitmapSource.Create(
imageWidth,
imageHeight,
dpiXDirection,
dpiYDirection,
format,
palette,
byteArray,
stride);
using (var ms = new MemoryStream())
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imageSource);
encoder.Save(ms);
var bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
//I can't just create a MemoryStream from the original byte array because there is no header info and it doesn't know how to decode the image!
bi.StreamSource = ms;
bi.DecodePixelWidth = 60;
bi.EndInit();
//This thumbnail is blurry!!!
Thumbnail = bi;
}
I'm guessing its blurry since I'm converting it to png first, but when I use the BmpBitmapEncoder I get that "No imaging component available" error. In this case my image is Gray8, but I'm not sure why the PngEncoder can figure it out but the BmpEncoder can't.
Surely there must be someway to create a thumbnail from the original ImageSource without having to encode it to a bitmap format first? I wish BitmapSource.Create just let you specify a decode width/height like the BitmapImage class does.
EDIT
The final answer is to use a TransformBitmap with a WriteableBitmap to create the thumbnail and eliminate the original, full-size image.
var imageSource = BitmapSource.Create(...raw bytes and stuff...);
var width = 100d;
var scale = width / imageSource.PixelWidth;
WriteableBitmap writable = new WriteableBitmap(new TransformedBitmap(imageSource, new ScaleTransform(scale, scale)));
writable.Freeze();
Thumbnail = writable;
You should be able to create a TransformedBitmap from the original one:
var bitmap = BitmapSource.Create(...);
var width = 60d;
var scale = width / bitmap.PixelWidth;
var transform = new ScaleTransform(scale, scale);
var thumbnail = new TransformedBitmap(bitmap, transform);
In order to get ultimately rid of the original bitmap, you could create a WriteableBitmap from the TransformedBitmap:
var thumbnail = new WriteableBitmap(new TransformedBitmap(bitmap, transform));

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);

Set System.Windows.Controls.Image from StreamReader?

I've got an image in PNG format in a StreamReader object. I want to display it on my WPF form. What's the easiest way to do that?
I've put an Image control on the form, but I don't know how to set it.
The Image.Source property requires that you supply a BitmapSource instance. To create this from a PNG you will need to decode it. See the related question here:
WPF BitmapSource ImageSource
BitmapSource source = null;
PngBitmapDecoder decoder;
using (var stream = new FileStream(#"C:\Temp\logo.png", FileMode.Open, FileAccess.Read, FileShare.Read))
{
decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
if (decoder.Frames != null && decoder.Frames.Count > 0)
source = decoder.Frames[0];
}
return source;
This seems to work:
image1.Source = BitmapFrame.Create(myStreamReader.BaseStream);
Instead of using a StreamReader, I would directly generate the Stream,
FileStream strm = new FileStream("myImage.png", FileMode.Open);
PngBitmapDecoder decoder = new PngBitmapDecoder(strm,
BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
myImage.Source = decoder.Frames[0];
where myImage is the name of your Image in XAML
<Image x:Name="myImage"/>
Update: If you have to use the StreamReader, you get the Stream by using .BaseStream.

Assign image to Image.Source

How to assign a picture Image.Source: Image.Source = "Images \ 1.bmp" - does not work (you can not assign a picture)
Image myImage3 = new Image();
BitmapImage bi3 = new BitmapImage();
bi3.BeginInit();
bi3.UriSource = new Uri("smiley_stackpanel.PNG", UriKind.Relative);
bi3.EndInit();
myImage3.Stretch = Stretch.Fill;
myImage3.Source = bi3;
As mentioned above easily found here
Refer to Pack URIs in WPF
Don't forget to set the Build Action for '1.bmp' to Resource
The Image.Source page at MSDN http://msdn.microsoft.com/en-us/library/system.windows.controls.image.source.aspx has an example. You need to assign an ImageSource, not a string. (but of course see Pack URIs in above post)

Resources