没有结果将System.Drawing.Image转换为System.Windows.Media.ImageSource [英] Converting System.Drawing.Image to System.Windows.Media.ImageSource with no result
问题描述
我想在WPF应用程序中将Image转换为ImageSource.我使用可以正常工作的Code128库(已在WinForms应用程序中检查过).下面的函数返回大小正确的ImageSource,但是看不到任何内容.
I would like to convert Image to ImageSource in my WPF app. I use Code128 library which works properly (already checked in WinForms app). Function below returns ImageSource with properly size, but nothing is visible.
private ImageSource generateBarcode(string number)
{
var image = Code128Rendering.MakeBarcodeImage(number, 1, false);
using (var ms = new MemoryStream())
{
var bitmapImage = new BitmapImage();
image.Save(ms, ImageFormat.Bmp);
bitmapImage.BeginInit();
ms.Seek(0, SeekOrigin.Begin);
bitmapImage.StreamSource = ms;
bitmapImage.EndInit();
return bitmapImage;
}
}
更新: 最好的方法是下面的克莱门斯评论的一种方法.比使用memorystream快约4倍.
UPDATE: The best method is one commented by Clemens below. About 4 times faster than using memorystream.
推荐答案
必须设置BitmapCacheOption.OnLoad
以确保在调用EndInit()
时立即加载BitmapImage.如果没有该标志,则流必须保持打开状态,直到实际显示BitmapImage.
You have to set BitmapCacheOption.OnLoad
to make sure that the BitmapImage is loaded immediately when EndInit()
is called. Without that flag, the stream would have to be kept open until the BitmapImage is actually shown.
using (var ms = new MemoryStream())
{
image.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.StreamSource = ms;
bitmapImage.EndInit();
return bitmapImage;
}
这篇关于没有结果将System.Drawing.Image转换为System.Windows.Media.ImageSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!