Resizing WritableBitmap

Harsha picture Harsha · Jul 21, 2010 · Viewed 8k times · Source

I have created a WriteableBitmap in Gray16 format. I want to resize this WriteableBitmap to my known dimention preserving the pixel format(Gray16).

Is any one worked on the Resizing the WriteableBitmap. Please help me.

I also searched the internet and found http://writeablebitmapex.codeplex.com/ but this through an assebmly reference error.

Please help me.

Answer

herohuyongtao picture herohuyongtao · Mar 11, 2014

You can use the following function to resize a writableBitmap:

WriteableBitmap resize_image(WriteableBitmap img, double scale)
{
    BitmapSource source = img;

    var s = new ScaleTransform(scale, scale);

    var res = new TransformedBitmap(img, s);

    return convert_BitmapSource_to_WriteableBitmap(res);
}

WriteableBitmap convert_BitmapSource_to_WriteableBitmap(BitmapSource source)
{
    // Calculate stride of source
    int stride = source.PixelWidth * (source.Format.BitsPerPixel / 8);

    // Create data array to hold source pixel data
    byte[] data = new byte[stride * source.PixelHeight];

    // Copy source image pixels to the data array
    source.CopyPixels(data, stride, 0);

    // Create WriteableBitmap to copy the pixel data to.      
    WriteableBitmap target = new WriteableBitmap(source.PixelWidth
        , source.PixelHeight, source.DpiX, source.DpiY
        , source.Format, null);

    // Write the pixel data to the WriteableBitmap.
    target.WritePixels(new Int32Rect(0, 0
        , source.PixelWidth, source.PixelHeight)
        , data, stride, 0);

    return target;
}