WriteableBitmapEx Resize function in WInRT

1.3k views Asked by At

I try to write function that will be resize images. I use WriteableBitmapEx for WinRT/Win8 function Resize();

public class PictureExtension 
{
    private MemoryRandomAccessStream _memoryRandomAccessStream;
    private readonly Stream _dataStream;
    private readonly double _height;
    private readonly double _width;

    public PictureExtension(Stream dataStream, double height, double width)
    {
        _dataStream = dataStream;
        _memoryRandomAccessStream = (_dataStream.ToRandomAccessStream());
        _height = height;
        _width = width;
    }

    public byte[] ToArray(double maxSide)
    {
        if (_height <= maxSide && _width <= maxSide)
        {
            return _dataStream.ToArray();
        }
        else
        {
            var target = new WriteableBitmap((int) _width, (int) _height);

            var aspectRatio = (double)_width / _height;
            double newHeight;
            double newWidth;
            if (_width > _height)
            {
                newWidth = maxSide;
                newHeight = newWidth / aspectRatio;
            }
            else
            {
                newHeight = maxSide;
                newWidth = maxSide * aspectRatio;
            }

            int count = (int)_dataStream.Length;

            using (var bmpStream = target.PixelBuffer.AsStream())
            {
                bmpStream.Seek(0, SeekOrigin.Begin);
                bmpStream.Write(_dataStream.ToArray(), 0, _dataStream.ToArray().Length);
            }


            var resized = target.Resize((int)newWidth, (int)newHeight, WriteableBitmapExtensions.Interpolation.Bilinear);

            return resized.ToByteArray();

        }

    }
}

}

This function return array of byte but it is not image any more.. I tested with PNG and JPG formats.. What's wrong?

3

There are 3 answers

0
Martin Suchan On BEST ANSWER

I've been examining this problem before, try the code in this thread:
How to resize Image in C# WinRT/winmd?

0
Filip Skakun On

Not sure if that would help you, but there is a LoadAsync() overload I wrote load a bitmap at the given decode resolution which might help you depending on your scenario.

http://winrtxamltoolkit.codeplex.com/SourceControl/changeset/view/0657c67a93d5#WinRTXamlToolkit%2fImaging%2fWriteableBitmapLoadExtensions.cs

0
Rene Schulte On

The best help would be if you follow your post at the CodePlex site ;) http://writeablebitmapex.codeplex.com/discussions/399624

No need for cross posting.