Liam McInroy
Liam McInroy

Reputation: 4366

Only top portion of image is saved

I'm using the following code to save a picture of a canvas

if (!Directory.Exists(DefaultSettings.MainPath + "//Skeleton Images//"))
    Directory.CreateDirectory(DefaultSettings.MainPath + "//Skeleton Images//");
System.Windows.Size size = new System.Windows.Size(canvas.Width, canvas.Height);
canvas.Measure(size);
canvas.Arrange(new System.Windows.Rect(size));
RenderTargetBitmap renderBitmap = new RenderTargetBitmap( (int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32);
renderBitmap.Render(canvas);
using (FileStream outstream = new FileStream(DefaultSettings.MainPath + "//Skeleton Images//Kinected (" + images + ").jpg", FileMode.Create))
{
    JpegBitmapEncoder cEncoder = new JpegBitmapEncoder();
    cEncoder.Frames.Add(BitmapFrame.Create(renderBitmap));
    cEncoder.Save(outstream);
}

However, it is only saving the top portion of the image. Although the image size is 321x240, and the canvas size is also the same size. Why is this happening? this same code used before saved the entire canvas, so why is this suddenly creating errors? Image below to illustrate the problem. Also note the canvas is placed on top of the image, as they are rendered seperately, and the canvas extends all the way down to the "Color Frame" text.

Only top portion saved

Upvotes: 2

Views: 141

Answers (2)

Hans Passant
Hans Passant

Reputation: 942448

Although the image size is 321x240, and the canvas size is also the same size

They do, but they don't use the same units. The bitmap size is in pixels, the canvas size is in units of 1/96 inches. Which tends to work fine since on many machines that's the same amount. But not when you run on a machine with a different dots-per-inch setting for the video adapter. Later versions of Windows make it very simple to change this, with pre-cooked selections for 125% and 150%. Like you did.

You have to create a bigger bitmap in pixels. Already well covered by this question.

Upvotes: 3

Aditi
Aditi

Reputation: 509

Try finding size in this manner:

private static Size SizeCalculation(Size image, Size boundingBox)
{       
    double widthScale = 0, heightScale = 0;
    if (image.Width != 0)
        widthScale = (double)boundingBox.Width / (double)image.Width;
    if (image.Height != 0)
        heightScale = (double)boundingBox.Height / (double)image.Height;                

    double scale = Math.Min(widthScale, heightScale);

    Size result = new Size((int)(image.Width * scale), 
                        (int)(image.Height * scale));
    return result;
}

See if you get proper size with this code and your code works for the image to fit into it.

Upvotes: 1

Related Questions