在银光Silverlight中,对于WriteableBitmap是本文的重点。这里将为大家讲解具体的实现过程,希望能对今后的开发工作有所帮助。
算法核心:对WriteableBitmap的所有像素点做循环遍历,然后存入Byte[]数组中,再转换为MemoryStream输出,下面是代码:
- Code
- private void ButtonSave_Click(object sender, RoutedEventArgs e)
- {
- WriteableBitmap bitmap = new WriteableBitmap(MyStackPanel, null);
- if (bitmap != null)
- {
- SaveFileDialog saveDlg = new SaveFileDialog();
- saveDlg.Filter = "JPEG Files (*.jpeg)|*.jpeg";
- saveDlg.DefaultExt = ".jpeg";
- if ((bool)saveDlg.ShowDialog())
- {
- using (Stream fs = saveDlg.OpenFile())
- {
- SaveToFile(bitmap, fs);
- MessageBox.Show("File save Complete");
- }
- }
- }
- }
- private static void SaveToFile(WriteableBitmap bitmap, Stream fs)
- {
- 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;
- }
- }
- FluxJpeg.Core.ColorModel model = new FluxJpeg.Core.ColorModel { colorspace = FluxJpeg.Core.ColorSpace.RGB };
- FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster);
- //Encode the Image as a JPEG
- MemoryStream stream = new MemoryStream();
- FluxJpeg.Core.Encoder.JpegEncoder encoder = new FluxJpeg.Core.Encoder.JpegEncoder(img, 100, stream);
- encoder.Encode();
- //Back to the start
- stream.Seek(0, SeekOrigin.Begin);
- //Get teh Bytes and write them to the stream
- byte[] binaryData = new Byte[stream.Length];
- long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);
- fs.Write(binaryData, 0, binaryData.Length);
- }
我对其中的这一段尤其不满意,自觉是性能的关键,有没有更高效的算法快速从WriteableBitmap直接得到像素的Byte[]数组?
- Code
- 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;
- }
- }
下面为演示代码,需要引入FJCore,如果您再编译的时候发现路径不正确,请出新引入一下,我已经那个把FJCoer放置在了压缩包中的refer文件夹下。
原文标题:Silverlight中,把WriteableBitmap转为Byte流并保存到本地
链接:http://www.cnblogs.com/zhangxuguang2007/archive/2009/11/05/1596721.html