2

我还有一个问题,我需要将字节数组转换为WriteableBitmap调整大小。我写下一个代码。

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);

}

调用后wb.Render(img, new ScaleTransform() { ScaleX = scale, ScaleY = scale });wb像素为零。

请帮忙。

4

2 回答 2

1
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);
}
于 2011-11-29T20:36:53.633 回答
0

尝试改变:

wb = new WriteableBitmap(0, 0);

至:

wb = new WriteableBitmap(maxWidth, maxHeight);
于 2011-11-29T20:07:34.187 回答