I have a Image in xaml that I'm trying to set the source of but I noticed the scale of the image when I read it in is getting changed which I do not want to happen. The goal is to get Image.Source to have the same width and height as the original image read in.
This is the Code I have so far
// Get a specific page then display it.
Emgu.CV.Mat[]? emguPageMats = CvInvoke.Imreadmulti(randomTestPreviewPath,
Emgu.CV.CvEnum.ImreadModes.Color);
Emgu.CV.Image<Bgr, byte> emguImage = emguPageMats[0].ToImage<Bgr, byte>();
Debug.Print(emguPageMats[0].Width + ", " + emguPageMats[0].Height); -> **returns 1700, 2200**
image.Source = ConvertBitmapToBitmapSource(emguImage.ToBitmap(), emguImage);
Debug.Print(image.Source.Width + ", " + image.Source.Height); -> **returns 1360, 1760**
Here is the conversion method im using which I found here on Stack Overflow that I renamed ConvertBitmapToBitmapSource()
public static BitmapSource ConvertBitmapToBitmapSource(System.Drawing.Bitmap bitmap,
Emgu.CV.Image<Bgr, byte> emguImage)
{
var bitmapData = bitmap.LockBits(
new System.Drawing.Rectangle(0, 0, emguImage.Width, emguImage.Height),
System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat);
var bitmapSource = BitmapSource.Create(
bitmapData.Width, bitmapData.Height,
bitmap.HorizontalResolution, bitmap.VerticalResolution,
PixelFormats.Bgr24, null,
bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
bitmap.UnlockBits(bitmapData);
return bitmapSource;
}
Thank you for taking the time to read this.
Edit 1: I found that the actual size of a BitmapSource is in BitmapSource.PixelWidth & BitmapSource.PixelHeight. Not sure how to get image.Source to become that size though...
Edit 2: Alright I think I got it. Could it be nicer? Probably.
// Get a specific page then display it.
Emgu.CV.Mat[]? emguPageMats = CvInvoke.Imreadmulti(randomTestPreviewPath,
Emgu.CV.CvEnum.ImreadModes.Color);
Emgu.CV.Image<Bgr, byte> emguImage = emguPageMats[0].ToImage<Bgr, byte>();
maxPages = emguPageMats.Count();
image.Source = ConvertBitmapToBitmapSource(emguImage.ToBitmap(), emguImage);
// Calculate Scaling using dpi.Y and dpi.Y are 120, guess it doesn't matter what I use
double d = (1d / 96) * dpi.X;
var finalWidth = image.Source.Width * d;
var finalHeight = image.Source.Height * d;
Debug.Print("final: " + finalWidth + ", " + finalHeight);
// Sets the width and height based on the dpi which is essentially pixelWidth & pixelHeight
image.Width = finalWidth;
image.Height = finalHeight;
Debug.Print("image: " + finalWidth + ", " + finalHeight);
This is for the dpi if anyone wants it.
public static System.Drawing.PointF dpi;
// For grabbing screen dpi to help with resizing the window
using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
{
dpi.X = graphics.DpiX;
dpi.Y = graphics.DpiY;
}