HowTo Get Rendered Image from WPF Image Control - wpf

Each WPF Image Control has RenderTransform Property that sets Scale, Skew, Rotate and many more Transformation to Images. After Calling RenderTransform Property, How to get Rendered Image into the BitmapImage or RenderTargetBitmap Class or Any other class?
This is my Code:
Dim InImage As New BitmapImage(New Uri("My Image Path"))
Dim TG As New TransformGroup
TG.Children.Add(New RotateTransform(190))
Dim MyImg As New Image
MyImg.Source = InImage
MyImg.RenderTransform = TG
'Here i need get Transformed Image into a BitmapImage or RenderTargetBitmap Variable or Any other class variable.

It's a pity that TransformedBitmap does not support rotation with angle other than any multiple of 90 degs (that means we can only rotate 90, 180, 270, ...). Thinking about which objects we can put in a bitmap and apply some Transform? Well we have DrawingGroup, DrawingVisual, ImageBrush, UIElement and via DrawingContext.
Using DrawingGroup, we have to put in an ImageDrawing and apply the transform via the Transform property of the DrawingGroup. Then we have to use a DrawingImage, set the Drawing property to the DrawingGroup.
Using DrawingVisual, we have to open a DrawingContext, use the DrawImage method after pushing some transform. Then we may have to use RenderTargetBitmap by passing the DrawingVisual in the Render method.
Using UIElement (like your idea about using Image control as the medium), we have to render the image on the UIElement. So an Image control suits this best. Every UIElement has a Transform property allowing us to add whatever transform. At last we also have to use a RenderTargetBitmap by passing the UIElement in the Render method.
Using ImageBrush, we have to set the ImageSource property to a BitmapImage. Then we can use the Transform or RelativeTransform property to apply some transform. After that we have to use a DrawingImage. Create a simple GeometryDrawing using the ImageBrush as its Brush, and a RectangleGeometry as its Geometry. Finally we just need to set this GeometryDrawing to the Drawing property of the DrawingImage. The output is the DrawingImage. I would like to use this approach to write the code here:
Dim InImage As New BitmapImage(New Uri("My Image Path"))
Dim ImgBrush As New ImageBrush(InImage)
ImgBrush.Viewport = New Rect(0.1,0.1,0.8,0.8)
ImgBrush.ViewportUnits = BrushMappingMode.RelativeToBoundingBox
Dim Rotating As New RotateTransform(190)
Rotating.CenterX = 0.5
Rotating.CenterY = 0.5
ImgBrush.RelativeTransform = Rotating
Dim ImgSize As New Rect(0,0,300,400)
Dim DrawImage As New DrawingImage()
DrawImage.Drawing = New GeometryDrawing(ImgBrush, null, ImgSize)
Note about the "My Image Path". I've found out that using a Relative image would not work if you don't have any Image folder at the same level with the built exe file. If you don't want to deploy some image folder together with your application, you can add your image as a Resource. To refer to an image added as a Resource in code behind, you have to use a special kind of path:
pack://application:,,,/Your_Relative_Image_Path
Note that to be sure your image is added as a Resource, try right clicking on the image (under the Projects treeview), select Properties in the popup menu, then look into the Build Action field, it should be Resource.
Also note about the ImgBrush.Viewport, setting it appropriately will prevent the image from being cut off (that's because the transformed image is rotated). It depends on the ImgSize and how much degree you rotate.

Related

WPF custom shader effect property binding for animation

I'm implementing transitions in a WPF application.
First I "save" my 2 FrameworkElement in 2 ImageBrush.
Then I set the Input & Back (Brush) properties of my shader Effect with them.
CustomEffect s = new CustomEffect();
RenderTargetBitmap rtb = new RenderTargetBitmap((int)SourceFrameWorkElement.ActualWidth, (int)SourceFrameWorkElement.ActualHeight, 96, 96, PixelFormats.Pbgra32);
rtb.Render(SourceFrameWorkElement);
ImageBrush ib = new ImageBrush(rtb);
s.Input = ib;
rtb.Render(TargetFrameWorkElement);
ib.ImageSource = rtb;
s.Back = ib;
SourceFrameWorkElement.Effect = s;
Now that all is set up, I want to animate the Time property of my shader, and i've tried this:
DoubleAnimation refDoubleAnimation = new DoubleAnimation(0.0, 1.0, Duration);
Storyboard.SetTarget(refDoubleAnimation, SourceFrameWorkElement);
Storyboard.SetTargetProperty(refDoubleAnimation, new PropertyPath("(Effect).(CustomEffect.Time)");
refStoryboard.Children.Add(refDoubleAnimation);
refStoryboard.Completed += new EventHandler(OnStoryboardCompleted);
refStoryboard.Begin(SourceFrameWorkElement, true);
and i get an InvalidOperationException on the begin method with this message:
"Cannot resolve all property references in the property path '(Effect).(CustomEffect.Time)'.
Verify that applicable objects supports the properties."
But when I use a built in Effect like BlurEffect, it works....
Can someone tell me where i'm wrong ?
Edit:
I've also tried
SourceElement.Effect.BeginAnimation(SlideInEffect.TimeProperty, refDoubleAnimation)
instead of using the storyboard, I don't get an exception but the second image pop instantly and the animation is not playing
The solution was to use BeginAnimation ^^
In fact, I had the second image with opacity to 1, and the animation was playing behind
(i checked if the time elapsed to get in my OnAnimationCompleted eventHandler matched with the transition Duration)
so i've created a second animation on the TargetElement opacity with 2 DiscreteDoubleKeyFrames to do the trick and now it works ^^
Maybe the Storyboard thing could work if i add the namespace in the PropertyPath but i have no time to test it so give it a try if you want, and update the post ^^.

How to specify the image scaling algorithm used by a WPF Image?

Is there a way to specify how an image is scaled up in an Image element with LayoutTransform set to a ScaleTransform with integer values for ScaleX and ScaleY?
I want to display the scaled image crisply (ie using 'nearest neighbour' scaling), with no blurring. (Imagine how you would want a bitmap editing program to behave when zooming in).
I noticed the protected property VisualBitmapScalingMode on Image, so created a subclass of Image that sets this property to BitmapScalingMode.NearestNeighbor. However, this had no effect.
You can set the RenderOptions.BitmapScalingMode property in the XAML for the Image control. There's no need to inherit the Image class.
I fixed this by overriding OnRender in my Image subclass, and setting the VisualBitmapScalingMode before drawing the image:
class MyImage : System.Windows.Controls.Image
{
protected override void OnRender(DrawingContext dc)
{
this.VisualBitmapScalingMode = System.Windows.Media.BitmapScalingMode.NearestNeighbor;
base.OnRender(dc);
}
}

WPF Image Formats and Binding

I have a project which requires be to convert an in memory System.Drawing.Bitmap into an in memory BitmapImage so I can bind the BitmapImage to an Image control via XAML. The problem I am running into is during the conversion the original bitmap gets shrunk and is very blurry.
This is very bad because the original bitmap is a bar code and I need this bar code to stay readable. Is there anything I can do to preserve the integrity of my bitmap? Or is it possible to bind a System.Drawing.Bitmap to an WPF Image control without first saving the bitmap and using a URI?
Also can anyone explain to me the difference between all these image formats? It seems as if there are a ton of them, they reside in numerous namespaces and it is a pain to convert between them.
EDIT.....
public static BitmapImage GetBitmapImage(Bitmap bmp)
{
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Bmp);
BitmapImage bmpI = new BitmapImage();
bmpI.BeginInit();
bmpI.StreamSource = ms;
bmpI.EndInit();
ms.Close();
ms.Dispose();
return bmpI;
}
Have you tried different bitmap scaling modes?
For example:
Image RenderOptions.BitmapScalingMode="HighQuality" ...
In my opinion, the easiest way to get rid of all those burdens is to create a user control, then put a
WindowsFormsHost
on to that control. After that you put a windows forms image to the host, and in the underlying code of the user control, you can create a dependency property to bind data and update changes to the image control.
Cheers.

Deleting a window's background image WPF

I'm having a problem in WPF where a window doesn't release it's file-lock on the background image file after closing, before another part of the application tries to write to the image.
So as an example; say I have a WPF app consisting of 3 windows, 1 "menu" selection window and 2 others. Both of the windows create an ImageBrush using a BitmapImage as the ImageSource (the same image).
Window A has a button that when pressed, cycles through the available background images by copying them each over the file used as the original ImageSource and creating a new ImageBrush and setting the Window.Background to the new brush.
Window B simply uses the ImageBrush to draw the Window.Background.
If Window A is launched, backgrounds switched, closed and then Window B launched, everything is fine.
If Window B is launched, closed, then Window A is launched and backgrounds switched it crashes. Trying to switch the backgrounds throws an IOException because:
"The process cannot access the file 'C:\Backgrounds\Background.png' because it is being used by another process."
So Window B must still be holding onto it somehow!? I have tried doing a GC.Collect(); GC.WaitForPendingFinalizers(); to see if that cures the problem but it doesn't.
The answer Thomas gave is correct, and works well if you have a file path, don't want to cache the bitmap, and don't want to use XAML.
However it should also be mentioned that BitmapImage has a built-in way to load the bitmap immediately by setting BitmapCacheOption:
BitmapImage img = new BitmapImage { CacheOption = BitmapCacheOption.OnLoad };
img.BeginInit();
img.UriSource = imageUrl;
img.EndInit();
or
<BitmapImage CacheOption="OnLoad" UriSource="..." />
This will load the bitmap immediately and explicitly close the stream, just as using a FileStream would, but with several differences:
It will work with any Uri, such as a pack:// Uri.
It can be used directly from XAML
The bitmap is cached in the bitmap cache, so future use of the same Uri won't go to the disk. In your particular application this may be a bad thing, but for other uses it may be a desirable feature.
I assume you're loading the image directly from the file, like that ?
BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = imageUrl;
img.EndInit();
Try to load it from a stream instead ; that way you can close the stream yourself after the image is loaded, so that the file isn't locked :
BitmapImage img = new BitmapImage();
using (FileStream fs = File.OpenRead(imageFilePath)
{
img.BeginInit();
img.StreamSource = fs;
img.EndInit();
}

Resize an Uploaded Image in Silverlight 3

I'm trying to resize an image in Silverlight 3 that has been submitted by a user via the OpenFileDialog control. I can grab the contents of the file and put it into a WriteableBitmap object and then display it on the screen just fine into an Image control. The Image control will even resize it to fit the size of the image control for me which is great.
The problem is the in memory image is still the original full resolution image, I kinda need to resize it in memory because I have a bunch of expensive operations I need to perform on it on a per pixel basis. So far I have the following code...
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
btnUploadPhoto.Click += new RoutedEventHandler(UploadPhoto_Click);
}
private void UploadPhoto_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image files (*.png;*.jpg;*.gif;*.bmp)|*.png;*.jpg;*.gif;*.bmp";
if (dialog.ShowDialog() == true)
{
WriteableBitmap bitmap = new WriteableBitmap(500, 500);
bitmap.SetSource(dialog.File.OpenRead());
imgMainImage.Source = bitmap;
txtMessage.Text = "Image size: " + bitmap.PixelWidth + " x " + bitmap.PixelHeight;
}
}
}
Problem is the WriteableBitmap class doesn't have a Resize method on it, and setting the height and width in the constructor doesn't seem to have any effect.
What you can do is create a new Image element and set its source to a Writeable bitmap created from the stream. Don't add this Image element to the visual tree. Create another WriteableBitmap of the final size you want. Then call Render on this WriteableBitmap passing the Image element and a ScaleTransform to resize the image to the appropriate size. You can then use the second WriteableBitmap as the source for a second Image element and add that to the visual tree. You can then allow the first Image and WriteableBitmap objects to get GCed so you get the memory back.
Have you looked at the WriteableBitmapEx project? It's an open source project with a tonne of extension methods for the WriteableBitmap class. Here's how you resize:
BitmapImage image = new BitmapImage();
image.SetSource(dialog.File.OpenRead());
WriteableBitmap bitmap = new WriteableBitmap(image);
WriteableBitmap resizedBitmap = bitmap.Resize(500, 500, WriteableBitmapExtensions.Interpolation.Bilinear);
// For uploading
byte[] data = resizedBitmap.ToByteArray();
I have used FJCore with some success, it's an open source C# imaging toolkit from Occipital. Includes in-memory resizing capability.
Also check out ImageMagick.

Resources