Silverlight中實(shí)現(xiàn)WriteableBitmap轉(zhuǎn)為Byte流
在銀光Silverlight中,對于WriteableBitmap是本文的重點(diǎn)。這里將為大家講解具體的實(shí)現(xiàn)過程,希望能對今后的開發(fā)工作有所幫助。
算法核心:對WriteableBitmap的所有像素點(diǎn)做循環(huán)遍歷,然后存入Byte[]數(shù)組中,再轉(zhuǎn)換為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);
- }
我對其中的這一段尤其不滿意,自覺是性能的關(guān)鍵,有沒有更高效的算法快速從WriteableBitmap直接得到像素的Byte[]數(shù)組?
- 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,如果您再編譯的時候發(fā)現(xiàn)路徑不正確,請出新引入一下,我已經(jīng)那個把FJCoer放置在了壓縮包中的refer文件夾下。
原文標(biāo)題:Silverlight中,把WriteableBitmap轉(zhuǎn)為Byte流并保存到本地
鏈接:http://www.cnblogs.com/zhangxuguang2007/archive/2009/11/05/1596721.html