Expand canvas / transparent background in BitmapImage in a WPF application

This is the next question about Save Image to save aspect format in a WPF application

I know how to scale an image, but how to increase the size of the canvas so that the image still has the required width and height. In this example, its 250x250, but its dynamics.

I created this illustration to show what I'm trying to do. alt text

I can’t find a way to expand the BitmapImage canvas, as well as a way to create the image in memory in the correct size with a transparent background, and then merge the two images together.

+5
source share
3 answers

CroppedBitmap, , , , WriteableBitmap. , , .

public static BitmapSource FitImage(BitmapSource input, int width, int height)
{
    if (input.PixelWidth == width && input.PixelHeight == height)
        return input;

    if(input.Format != PixelFormats.Bgra32 || input.Format != PixelFormats.Pbgra32)
        input = new FormatConvertedBitmap(input, PixelFormats.Bgra32, null, 0);

    //Use the same scale for x and y to keep aspect ratio.
    double scale = Math.Min((double)width / input.PixelWidth, height / (double)input.PixelHeight);

    int x = (int)Math.Round((width - (input.PixelWidth * scale))/2);
    int y = (int)Math.Round((height - (input.PixelHeight * scale))/2);


    var scaled = new TransformedBitmap(input, new ScaleTransform(scale, scale));
    var stride = scaled.PixelWidth * (scaled.Format.BitsPerPixel / 8);

    var result = new WriteableBitmap(width, height, input.DpiX, input.DpiY, input.Format,null);

    var data = new byte[scaled.PixelHeight * stride];
    scaled.CopyPixels(data, stride, 0);
    result.WritePixels(new Int32Rect(0,0,scaled.PixelWidth,scaled.PixelHeight), data, stride,x,y);
    return result;
}

RenderTargetBitmap, ViewBox , , .

+6

Stretch Uniform.

0

- , .

if (file.PostedFile != null)
{
    //write the new file to disk
    string cachePath = String.Format("{0}temp\\", Request.PhysicalApplicationPath);
    string photoPath = String.Format("{0}temp.png", cachePath);                
    if (!Directory.Exists(cachePath))
{
   Directory.CreateDirectory(cachePath);
}    

file.PostedFile.SaveAs(photoPath);

//resize the new file and save it to disk               
BitmapSource banana = FitImage(ReadBitmapFrame(file.PostedFile.InputStream), 640, 480);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(banana));
FileStream pngStream = new FileStream(cachePath + "test.png", FileMode.Create);
encoder.Save(pngStream);
pngStream.Close();

//set a couple images on page to the newly uploaded and newly processed files
image.Src = "temp/temp.png";
image.Visible = true;
image2.Src = "temp/test.png"; 


   image2.Visible = true;
}
0

All Articles