以下代码片段皆用到如下代码,故提取出来放在前面,以免重复
MemoryStream ms = new MemoryStream(bmpImgBuf); //bmpImgBuf为bmp图像缓冲区包含BMP头和图像数据(图像可来自文件、网络、或者设备等)
1. 不做转换,直接显示
BitmapFrame bmf = BitmapFrame.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.Default);
this.imgViewer.Source = bmf; //imgViewer为Image图像控件
2. 伸缩变换,然后显示
方式1).
var imgDecoder = BitmapDecoder.Create(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
var img = imgDecoder.Frames[0];
var target = new TransformedBitmap(img,
new ScaleTransform(
-640 / img.Width * 96 / img.DpiX, //如果宽度小于原图像宽度,则宽度方向被缩小,反之则放大,为负值,则叠加翻转变换
360 / img.Height * 96 / img.DpiY, //同上
0, 0));
this.imgViewer.Source = target;
方式2).
TransformedBitmap tbm = new TransformedBitmap();
tbm.BeginInit();
tbm.Source = BitmapFrame.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.Default);
ScaleTransform st = new ScaleTransform();
st.ScaleX = -1; //mirrow image on vertical direction
tbm.Transform = st;
tbm.EndInit();
this.imgViewer.Source = tbm;