Automatically crop and resize an image - c#

I Need to crop and resize an Image in my WPF application as soon as the Picture is loaded.
So, my Basic Image has a VGA size (640x480), and I Need to crop the edges (top by 18 Pixels, bottom by 36 Pixels, left by 48 Pixels, and right by 24 pixels). The new image (which is 568 x 426 pixels) Need to be refitted into the original size (640 x 480 pixels) - basically it's like a digital zoomc that we're using in photography.
I've already found some sample code (Cropping whitespace from image in C#) - this is however a Little bit too complicated since I don't Need to detect the Whitespace on the image. Is there any simple algorithm just by using XAML to do this ?
Thanks in advance.

I think that you should be able to do that by using the Viewbox Class. From the linked page: Defines a content decorator that can stretch and scale a single child to fill the available space. You literally add one to your Window and set your Image as the contents and then you can set properties to control which part of the image it displays:
<ViewBox Width="500" Height="500" Stretch="Uniform">
<Image Source="Images/SomeImage.jpg" Width="300" Height="300"
Margin="-48,-18,-36,-24" />
</ViewBox>
Experiment with the different StretchDirection values and set the Margin to negative values to crop. There are examples in the linked page, but let me know if you need more help.

Related

In Xamarin Form XAML page, how can I set the width of an Image equal to screen width?

I want to set the width of an Image to the width of the screen with 20 DP on both sides with the original aspect ratio in a XAML file (Xamarin Form), I hope it can be device-independent, which on any device, the Image width is the same as the screen width with 20 DP on both sides while maintaining its aspect ratio.
I tried WidthRequest, but it doesn't work.
'<Image x:Name="myImgBox"
HorizontalOptions="Center" />'
Thank you for the help!
SCREENSHOT of the PROBLEM
If you set the HorizontalOptions to FillAndExpand, the image will fill the space available horizontally. You can also change the VerticalOptions.
<Image Source="yourImage.png"
HorizontalOptions="FillAndExpand"
Aspect="Fill" > </Image>
The Aspect property determines how the image will be scaled to fit the display area:
Fill - Stretches the image to completely and exactly fill the display area. This may result in the image being distorted.
AspectFill - Clips the image so that it fills the display area while preserving the aspect (ie. no distortion).
AspectFit - Letterboxes the image (if required) so that the entire image fits into the display area, with blank space added to the top/bottom or sides depending on whether the image is wide or tall.

How to display SkeletonStream on a DepthStream or ColorStream Kinect Wpf

I would like to know how to overlay two Image objects in Wpf. I've made two streams which output a video, one for bones and another just a normal video. Now I would like to add them together, so the skeleton would be displayed on the color video.
A part of my XAML code is
<Grid Name="layoutGrid">
<Grid Name="VideoGrid" ClipToBounds="True" Background="AliceBlue">
<Image Name="ColorImage" Width="640" Height="480"/>
<Image Name="SkeletalImage" Width="640" Height="480"/>
<Canvas Background="Transparent"/>
</Grid>
<StatusBar VerticalAlignment="Bottom" HorizontalAlignment="Center">
<Button Name="Button1" Content="Skeleton Only" Width="120"/>
</StatusBar>
</Grid>
When I do this, only the Skeletal image is displayed and if I switch the both Images then the color image is shown. It seems like Canvas background doesn't do the trick (to make the black part of skeletal image transparent)
I thought the problem was in my XAML code but it was actually at drawing the transparent background to set the render size. The background for skeleton image was black
dc.DrawRectangle(Brushes.Black, null,
new Rect(0.0, 0.0, RenderWidth, RenderHeight));
instead of transparent
dc.DrawRectangle(Brushes.Transparent, null,
new Rect(0.0, 0.0, RenderWidth, RenderHeight));
that fixed my problem.
Thanks though
I've tried overlaying Skeletal onto color or depth on a canvas, but it never worked out. Instead, when I looked at the Kinect Explorer sample application in the SDK 1.6.0, they overlay using a grid. Unfortunately, I have not learned that much yet, but they used a grid for the color and depth, and a canvas for the skeletal tracking. I can post a snippet if it helps. Good luck!
You are asking basically two different questions: 1) How to display SkeletonStream on a DepthStream, which is very easy, 2) How to display SkeletonStream on a ColorStream, which is still easy but a little more complicated.
Answer to Question 1) The XYZ Vectors of the joints in the skeletal streams are in the same coordinate system as the Depth Stream. So if you plot the Deapth Stream as a quadratic mesh using the focal length of the depth camera from the Kinect SDK, you can plot the skeleton as a line plot in the same coordinate system. The source code that implements exactly what you want to do in OpenGL is available here that will give you an idea how to implement this in wpf.
Answer to Question 2) The video camera has a different field of view from the depth camera. To display the skeleton stream to the ColorStream you need first to map the XYZ vectors of the joints in the skeletal streams to the coordinate system of the depth stream and then draw first the video frame in the background and the skeleton as a line plot on the front.
You can easily do the mapping using the U-V texture coordinates given by the Kinect SDK. See how you can get the UV here.

WinRT: How do I ensure Images are drawn in a pixel-perfect way on a Canvas?

I am adding Image instances to a Canvas in Windows Runtime environment and my image keeps getting scaled up when in 140 and 180 scale resolution displays, it looks perfect in scale resolution 100. I tried creating 3 PNG images, one for each scale size: 100, 140, 180 but it still scales them up and they look blurry. I created a test image with 4 black pixels on a cyan background and I took a screenshot from the simulator, see how the image is blurry, my original image has just 4 perfect black pixels:
I tried changing the stretch mode of my Image objects, but it does nothing. I'm using this code to add the images at runtime:
var bitmapImage = new BitmapImage();
StorageFile bitmapFile = await StorageFile.GetFileFromApplicationUriAsync(imageUri);
await bitmapImage.SetSourceAsync(await bitmapFile.OpenReadAsync());
Image image = new Image{ Source = bitmapImage};
image.SetValue(Canvas.LeftProperty, x);
image.SetValue(Canvas.TopProperty, y);
canvas.Children.Add(image);
How do I get the images to draw pixel perfectly in the canvas without scaling and at the exact x/y coordinates I want?
I think I have a workaround, but it requires two steps:
First I have to load the image using a more a standard way that doesn't involve getting the file path like so.
var bitmapImage = new BitmapImage(imageUri);
Somehow this must retain more information internally that this image came from a file with the corresponding ResolutionScale for the current display. Thus when it is drawn by the canvas it is not scaled at all. However this only solves half the problem.
The next problem is that the x, y coordinates used to specify where the image is drawn are being scaled so the image is drawn in the wrong place, further than where I wanted. The only thing I can figure to do is unscale them first like so:
var resScale = DisplayInformation.GetForCurrentView().ResolutionScale;
Image image = new Image{ Source = bitmapImage};
image.SetValue(Canvas.LeftProperty, (x * 100.0) / (int)resScale);
image.SetValue(Canvas.TopProperty, (y * 100.0) / (int)resScale);
canvas.Children.Add(image);
The whole thing seems a bit crazy but it seems to work so far... Anyone have a better solution or an explanation why all this is necessary? Seems like the Canvas class needs an unscaled mode that doesn't mess with the images or coordinates across different resolution displays.
UPDATE: This doesn't work perfectly, using a double to store the value results in precision loss and sometimes there are anti-aliasing artifacts. This is not acceptable if you want pixel perfect graphics. I am still looking for a perfect solution.
There are a few more things that might help with your solution.
Use UseLayoutRounding="False" on your image.
Put your Canvas in a full-screen Viewbox, then set the Canvas Width and Height to the screen resolution. You'd use unscaled Canvas.Left/Top values in this case.
Use Direct2D/Direct3D for rendering.
Good luck.
You can change the Stretch property to "None", If you image is still meshed-up:
You should look at what DPI it is saved on. WPF tries to be DPI-independend, so it tries to draw an image of 5"x5" on every monitor the same size. Even when the resolution is higher, it still should be 5"x5" only a high resolution would render(rasterize) the image in higher quality.
Here's some info: http://www.wpflearningexperience.com/?p=41
How do I convert a WPF size to physical pixels?
Here's a piece of xaml code
you can always use scale transform from code behind to scale the images to appropriate amount be it less or more.
<Image Canvas.Left="150" Height="170" Width="170" Visibility="Visible" Stretch="None">
<Image.Source >
<BitmapImage UriSource="ms-appx:///Assets/rollingDieSprite.png"></BitmapImage>
</Image.Source>
<Image.RenderTransform>
<ScaleTransform ScaleX="4" ScaleY="4" x:Name="scaleTfDie"></ScaleTransform>
</Image.RenderTransform>
</Image>
in c# code behind you can go for the following
ScaleTransform sc = new ScaleTransform();
sc.ScaleX = 0.9;
sc.ScaleY = 0.9;
imgDieRolling.RenderTransform = sc;
this will control the scaling . try using fill=none . Let me know if it works.
I found this issue quite problematic as well. I'm creating custom bitmaps and drawing them at different positions on the canvas. I couldn't find a way in the XAML, but I found a way using Direct2D. When you set up your D2DContext, there's a function called SetUnitMode(). The default unit mode is "DIPS" which causes all drawing to be scaled. By switching to PIXELS mode, the system stops scaling the drawing and does everything 1:1.
m_d2dContext->SetUnitMode(D2D1_UNIT_MODE_PIXELS);

Kinect show Depth Image in Full Screen

Is there a way to show Kinect Depth Image into Full Screen mode? I'm using C# and WPF, the OpenNI C++ example able to show the dept image in full size with out any stretch occur, but when I use WPF, the image gets stretch out.
Currently I'm getting resolution of 640X480, but I want to display it into any screen size or maybe TV. My laptop is 1280X768 but when u make the image full size it get stretced.
Thanks in advance.
As far as I know the hardware resolution of the Kinect cameras is 640 x 480 so there is no way to increase that without stretching.
In WPF it is possible to scale the image in proportion so the dots of the image remain square.
<Image Source="..." Stretch="Uniform" />
or not scale at all:
<Image Source="..." Stretch="None" />
See Stretching Images under Displaying Images in WPF

Image in WPF getting Blurry

I am developing an application in WPF using C#. I am putting Images in a WrapPanel and showing inside a Grid with one more Border and using images in Buttons also. Problem is my Image control loosing its quality. I am not able to post my image here so I am simply describing here.
I used SnapsToDevicePixels="True" for the images but still it looks blurry.
Updated:
Here I shared the Image below:
I think what Markus told is the one way to resolve your issue and try by adding one more property in it RenderOptions.EdgeMode="Aliased" for each image I mean :
<Image Source="/LoginPanel;component/Icons/icoLogin.ico"
RenderOptions.BitmapScalingMode="NearestNeighbor"
RenderOptions.EdgeMode="Aliased"/>
if you still not able to fix your problem then you can refer this http://blogs.msdn.com/b/dwayneneed/archive/2007/10/05/blurry-bitmaps.aspx to create a custom Bitmap class and apply on all Images which are creating trouble for you.
You can also see this Stack Overflow Question
SnapsToDevicePixels seems not working for bitmaps.
The NearestNeighbor options actually converts the bitmap and will end up with different one to the original bitmap.
In WPF 4, a property "UseLayoutRounding" on the FrameworkElement is introduced to solve this problem.
By setting this property to True on your root element, such as Window will align children elements on the edges of pixels.
<Window UseLayoutRounding="True">...</Window>
This works for me
<Image Source="/LoginPanel;component/Icons/icoLogin.ico"
RenderOptions.BitmapScalingMode="NearestNeighbor"</Image>
Set RenderOptions.BitmapScalingMode="NearestNeighbor" for each image. Alternatively see this question here on StackOverflow.
Edit:
Here is my sample code
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="661">
<WrapPanel>
<Button VerticalAlignment="Center">
<Image Source="/WpfApplication1;component/icoChip32x32.ico"
RenderOptions.BitmapScalingMode="NearestNeighbor" Stretch="None"></Image>
</Button>
<Button VerticalAlignment="Center">
<Image Source="/WpfApplication1;component/icoChip32x32.ico"
RenderOptions.BitmapScalingMode="NearestNeighbor" Stretch="None"></Image>
</Button>
<Button VerticalAlignment="Center">
<Image Source="/WpfApplication1;component/Presentation-Edit.png"
RenderOptions.BitmapScalingMode="NearestNeighbor" Stretch="None"></Image>
</Button>
<Button VerticalAlignment="Center">
<Image Source="/WpfApplication1;component/Presentation-Edit.png"
RenderOptions.BitmapScalingMode="NearestNeighbor" Stretch="None"></Image>
</Button>
</WrapPanel>
</Window>
And this is my result:
Use UseLayoutRounding="True" property on the parent element if image is used as a content. In your case it is the Button.
I ran into a blurriness issue with image backgrounds caused by scaling and the solution was much simpler than you may think. While at first I wondered if it was being scaled up to a power-of-two texture size, the scaling actually matched the ratio of System DPI (96) : Image DPI (72, which is the default for many editors). If you adjust the image to 96 DPI it should display pixel-perfect with the default Windows settings.
EDIT: Tried an image with high detail contrast and it is slightly softened.
WPF doesn't use concrete pixel values for sizes and positioning, so that it can scale well with DPI.
This can lead to a problem where it tries to use a position that doesn't correspond to a discrete on-screen pixel; some of the image pixels are rendered over multiple on-screen pixels which we see as blurring.
UseLayoutRendering=true with SnapToDevicePixels=false should solve this issue. You also need to set it at the main window level too, so that the calculations cascade down to the image level.
You can try this out by creating a simple WPF application with one window, and your images. Setting the image margin to be something silly like (10.452, 0.736, 0, 0) will lead to blurring. This goes away with UseLayoutRendering=true on the image.
If you then set the margin again in your window's constructor after InitializeComponent(), it is blurry regardless of whether you set UseLayoutRendering=true on the image, since the calculations to line up with on-screen pixels were made before you then moved the image to a location which doesn't match up with these.
I'm not entirely sure what the difference is between UseLayoutRendering and SnapToDevicePixels - I think it is just the time that the calculations are made. UseLayoutRendering seems to be preferable for images.
Stretching/squashing an image from its original size can also lead to blurring problems.
I had the same Problem, but in my case I've downloaded Icons and found out, that they all had wrong DPI too... 110,56 and 116,xx and 95,99 etc...
When i changed the DPI to 96 for all, everything was fine!

Categories

Resources