zlb

silverlight3把page中的控件的内容转为位图另存到本地

因为项目需要这个功能

 private void btnChartPrint_Click(object sender, RoutedEventArgs e)
         {
             UIElement cnvSource 
= this.gridChartPrint as UIElement;
             WriteableBitmap bitmap 
= new WriteableBitmap(cnvSource, new TranslateTransform());
             
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(
"Complete","提示",MessageBoxButton.OK);

                     }
                 }
             }
          
使用silverlight中的保存对话框

using FluxJpeg.Core;这是个开源组件 可以在google的开源网站找到

  private static void SaveToFile(WriteableBitmap bitmap, Stream fs)
         {
             
int width = bitmap.PixelWidth;
             
int height = bitmap.PixelHeight;
             
int bands = 3;
             
byte[][,] raster = new byte[bands][,];

             
//Convert the Image to pass into FJCore
             
//Code From http://stackoverflow.com/questions/1139200/using-fjcore-to-encode-silverlight-writeablebitmap
             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  改为 FluxJpeg.Core.ColorMode
              FluxJpeg.Core.ColorModel model = new FluxJpeg.Core.ColorModel { colorspace = 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);

posted on 2009-09-08 10:32  zlb  阅读(886)  评论(1编辑  收藏  举报

导航