使用mvvm从Image Control获取加载的Image [英] Get the loaded Image from Image Control using mvvm
问题描述
我在检索WPF图像控件中显示的图像时出现问题
I have a problem with retrieving the image shown in my WPF Image Control
<Image x:Name="img" RenderTransformOrigin="0.5, 0.5" Source="{Binding ImageSource, Source={x:Static vm:ItemProvider.instance}, UpdateSourceTrigger=PropertyChanged}" >
<Image.RenderTransform>
<RotateTransform CenterX="0" CenterY="0" Angle="{Binding ElementName=ScrollBar, Path=Value}" />
</Image.RenderTransform>
</Image>
我使用滚动条旋转图像
我想检索它,如控件所示
And i want to retrieve it as shown in the control
这是我如何将图像加载到图像控件
this is how i load image to the Image Control
private byte[] _ImageSource;
public byte[] ImageSource
{
get { return _ImageSource; }
set
{
_ImageSource = value;
RaisePropertyChanged("ImageSource");
}
}
我正在尝试检索图片中显示的图片获取 ImageSource
进行控制,但它们不一样。我将图像旋转90度。但是当我加载它时,返回的图像是相同的。
I am trying to retrieve the image shown in the Image Control by getting the ImageSource
but they are not the same. I rotate the Image 90 degrees. But the return Image is the same when i load it.
但是使用后面的代码我可以像这样访问图像
but using code behind i can access the image like this
img.Source
然后我将源转换为字节数组
img.Source
then i convert the source into byte array
推荐答案
旋转Image元素不会在其Source属性中旋转ImageSource。
Rotating the Image element does in no way rotate the ImageSource in its Source property.
要创建旋转的ImageSource,请使用 TransformedBitmap
:
To create a rotated ImageSource, use a TransformedBitmap
:
var sourceBitmap = new BitmapImage();
using (var stream = new MemoryStream(ImageSource))
{
sourceBitmap.BeginInit();
sourceBitmap.CacheOption = BitmapCacheOption.OnLoad;
sourceBitmap.StreamSource = stream;
sourceBitmap.EndInit();
}
// This should be another view model property that the Slider is bound to.
// Only multiples of 90 degrees are valid values.
var rotationAngle = 90d;
var rotation = new RotateTransform(rotationAngle);
var rotatedBitmap = new TransformedBitmap(sourceBitmap, rotation);
为避免您必须创建新来源每次转换的位图,您应该将ImageSource属性的类型从 byte []
更改为 ImageSource
。
为了将其写回另一个 byte []
,请使用 BitmapEncoder之一
类,例如 PngBitapEncoder
。
In order to write this back into another byte[]
, use one of the BitmapEncoder
classes, e.g. PngBitapEncoder
.
这篇关于使用mvvm从Image Control获取加载的Image的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!