Reputation: 81
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>
I rotate the Image using Scrollbar
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");
}
}
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
then i convert the source into byte array
Upvotes: 0
Views: 365
Reputation: 128013
Rotating the Image element does in no way rotate the ImageSource in its Source property.
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);
To avoid that you have to create a new source bitmap for every conversion, your should change the type of your ImageSource property from byte[]
to ImageSource
.
In order to write this back into another byte[]
, use one of the BitmapEncoder
classes, e.g. PngBitapEncoder
.
Upvotes: 1