Home >

Silverlight 3 WriteableBitmap to Jpg

17. July 2009

Andy Beaulieu had posted how to "print" from Silverlight 3 using a WriteableBitmap that's converted to a png image (post here.) I wanted to use a jpeg image. After looking around found the FJCore library which provides jpeg encoding/decoding. After struggling with how to convert the pixel array from WriteableBitmap to the format that FJCore expects I finally got it working. Here is the code if anyone is interested.

 

private static string GetBase64Jpg(WriteableBitmap bitmap)
{
    int width = bitmap.PixelWidth;
    int height = bitmap.PixelHeight;
    int bands = 3;
    byte[][,] raster = new byte[bands][,];

    for (int i = 0; i < bands; i++)
    {
        raster[i] = new byte[width, height];    
    }

    for (int row = 0; row < height; row++)
    {
        for (int column = 0; column < width; column++)
        {
            int pixel = bitmap.Pixels[width * row + column];
            raster[0][column, row] = (byte)(pixel >> 16);
            raster[1][column, row] = (byte)(pixel >> 8);
            raster[2][column, row] = (byte)pixel;
        }
    }

    ColorModel model = new ColorModel { colorspace = ColorSpace.RGB };
    FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster);
    MemoryStream stream = new MemoryStream();
    JpegEncoder encoder = new JpegEncoder(img, 90, stream);
    encoder.Encode();

    stream.Seek(0, SeekOrigin.Begin);
    byte[] binaryData = new Byte[stream.Length];
    long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);

    string base64String =
            System.Convert.ToBase64String(binaryData,
                                          0,
                                          binaryData.Length);

    return base64String;
}

Comments

9/29/2009 11:19:15 PM #
Silverlight 3 WriteableBitmap to Jpg  , fascinated me. I have recently started out to develop utilizing Silverlight but  am realising it is a big learning curve.  My recent experience is with php, mysql, most linux based tools and flash. The ambition of employing Silverlight to produce a clear visual design which runs speedily in all the established browsers, IE, Safari, Firefox and Google Chrome seems a big head ache that I find is taking numerous hours to master.  Absorbing to read your thoughts and the comments in your site on Silverlight.  I find the tutorial web sites and Microsofts Silverlight site are rigid and address the same items, dialog in blogs often addresses effective methods to beat issues that takes me through the learning curve more rapidly.  Thanks for the note, it has assisted in a small way to get me through the migration.
10/17/2009 11:58:13 PM #
Silverlight 3.0 中的 WriteableBitmap

Silverlight3.0中的WriteableBitmap尽管矢量图形非常的强大但是在有些情况下还是需要用到位图,因为他们在运行时能得到更高的执行效率和渲染效果。在Silverlight2...