Artem Holodnyak
Artem Holodnyak

Reputation: 31

Issue with rendering WriteableBitmap from Image in Silverlight

I have a next problem, I need to convert array of bytes to WriteableBitmap with resize. I write next code.

private byte[] ResizeImage(byte[] array, double maxWidth, double maxHeight)
{
    WriteableBitmap wb = null;

    var stream = new MemoryStream(array);
    stream.Seek(0, SeekOrigin.Begin);
    var bmp = new WriteableBitmap(0, 0);
    bmp.SetSource(stream);
    stream.Close();
    var img = new Image();
    img.Source = bmp;
    double scaleX = 1;
    double scaleY = 1;
    if (bmp.PixelHeight > maxHeight)
    {
        scaleY = maxHeight / bmp.PixelHeight;
    }
    if (bmp.PixelWidth > maxWidth)
    {
        scaleX = maxWidth / bmp.PixelWidth;
    }
    wb = new WriteableBitmap(0, 0);
    var scale = Math.Min(scaleY, scaleX);
    wb.Render(img, new ScaleTransform() { ScaleX = scale, ScaleY = scale });
    wb.Invalidate();
    return Utils.Encode(wb);

}

After call wb.Render(img, new ScaleTransform() { ScaleX = scale, ScaleY = scale });, wb has zero pixels.

Help please.

Upvotes: 2

Views: 1720

Answers (2)

David
David

Reputation: 1062

private byte[] ResizeImage(byte[] array, int maxWidth, int maxHeight)
{
    var stream = new MemoryStream(array);
    stream.Seek(0, SeekOrigin.Begin);

    var bmp = new BitmapImage();
    bmp.SetSource(stream);
    stream.Close();
    var img = new Image();
    img.Source = new BitmapImage();

    double scaleX = 1;
    double scaleY = 1;
    if (bmp.PixelHeight > maxHeight)
    {
        scaleY = maxHeight / bmp.PixelHeight;
    }
    if (bmp.PixelWidth > maxWidth)
    {
        scaleX = maxWidth / bmp.PixelWidth;
    }

    WriteableBitmap wb = new WriteableBitmap(maxWidth, maxHeight);
    var scale = Math.Min(scaleY, scaleX);
    wb.Render(img, new ScaleTransform() { ScaleX = scale, ScaleY = scale });
    wb.Invalidate();

    return Utils.Encode(wb);
}

Upvotes: 1

p.wilt
p.wilt

Reputation: 536

Try changing:

wb = new WriteableBitmap(0, 0);

To:

wb = new WriteableBitmap(maxWidth, maxHeight);

Upvotes: 0

Related Questions