Search code examples
c#wpfimagememorystreambitmapimage

Multiply Image Source From MemoryStream


I use the follwing code to Convert a an image file to 96 DPI and use it as a background.

BitmapSource bitmapSource = ConvertBitmapTo96Dpi(CompleteBackgroundImage);
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();

encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(memoryStream);

memoryStream.Position = 0;

CompleteBackgroundImage = new BitmapImage();
CompleteBackgroundImage.BeginInit();
CompleteBackgroundImage.StreamSource = memoryStream;
CompleteBackgroundImage.CacheOption = BitmapCacheOption.OnLoad;
CompleteBackgroundImage.DecodePixelHeight = (int)Math.Round(finalHeight, MidpointRounding.AwayFromZero);
CompleteBackgroundImage.DecodePixelWidth = (int)Math.Round(finalWidth, MidpointRounding.AwayFromZero);
CompleteBackgroundImage.EndInit();

memoryStream.Close();

Now I want, if the screen is bigger than the file, to multiply the image into one Image, so I can use it as a background. So if my screen is 1920 x 1080 and the image is only 500 x 500, I want that picture as big as 2000 x 1500 and the original image must be shown 4 times from left to right and 3 times from up to down.

But how should I do that?


Solution

  • Consider using an ImageBrush with TileMode set to Tile:

    <Window.Background>
        <ImageBrush TileMode="Tile" ViewportUnits="Absolute" Viewport="0,0,512,384">
            <ImageBrush.ImageSource>
                <BitmapImage UriSource="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg"/>
            </ImageBrush.ImageSource>
        </ImageBrush>
    </Window.Background>
    

    Or shorter:

    <Window.Background>
        <ImageBrush TileMode="Tile" ViewportUnits="Absolute" Viewport="0,0,512,384"
                    ImageSource="C:\Users\Public\Pictures\Sample Pictures\Koala.jpg"/>
    </Window.Background>