SilverLight保存统计图到服务器
刚前面写的是保存charting生成的图片到本地的,因为需要服务器的将图片放到word文档中,所以必须要在服务器中生成图片
而我的应用时发布在weblogic中的,所以需要一些配置(如果不是java平台的,或者无视我吧)
1.XX.Web下面添加WEB-INF目录
2.将流上传
3.XX.Web下面添加自己写的解析流的jsp文件
4.测试一下
这里是Silverlight的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.DataVisualization.Charting;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using System.IO;
using FluxJpeg.Core;
using System.Windows.Browser;
namespace SLChatSaveImg
{
public partial class MainPage : UserControl
{
//其他样式可以参考http://www.comesns.com/bencandy.php?fid=54&id=721
DispatcherTimer t;//线程
public class Complex
{
public string Key { set; get; }
public int Value1 { set; get; }
public int Value2 { set; get; }
public int Value3 { set; get; }
public int Value4 { set; get; }
}
public MainPage()
{
InitializeComponent();
listadd();
}
private List<Complex> listadd()
{
return new List<Complex>() {
new Complex{Key="key1",Value1=1,Value2=6,Value3=6,Value4=-2},
new Complex{Key="key2",Value1=2,Value2=7,Value3=5,Value4=-3},
new Complex{Key="key3",Value1=3,Value2=8,Value3=4,Value4=-4},
new Complex{Key="key4",Value1=4,Value2=9,Value3=3,Value4=-5},
new Complex{Key="key5",Value1=1,Value2=10,Value3=2,Value4=-6},
new Complex{Key="key6",Value1=3,Value2=1,Value3=4,Value4=-3}
};
}
private void button1_Click(object sender, RoutedEventArgs e)
{
chart.Series.Clear();
if ("1".Equals(textBox1.Text))
{
ColumnSeries columnSeries = new ColumnSeries();
columnSeries.Title = "33333333";
columnSeries.IndependentValueBinding =
new System.Windows.Data.Binding("Key");
columnSeries.DependentValueBinding =
new System.Windows.Data.Binding("Value3");
columnSeries.ItemsSource = listadd();
chart.Series.Add(columnSeries);
ColumnSeries columnSeries2 = new ColumnSeries();
columnSeries2.Title = "4444444444";
columnSeries2.IndependentValueBinding =
new System.Windows.Data.Binding("Key");
columnSeries2.DependentValueBinding =
new System.Windows.Data.Binding("Value4");
columnSeries2.ItemsSource = listadd();
chart.Series.Add(columnSeries2);
LineSeries lineSeries = new LineSeries();
lineSeries.Title = "1111111111";
textBox1.Text = "LineSeries";
lineSeries.IndependentValueBinding =
new System.Windows.Data.Binding("Key");
lineSeries.DependentValueBinding =
new System.Windows.Data.Binding("Value1");
lineSeries.ItemsSource = listadd();
chart.Series.Add(lineSeries);
LineSeries lineSeries2 = new LineSeries();
lineSeries2.Title = "22222222";
lineSeries2.IndependentValueBinding =
new System.Windows.Data.Binding("Key");
lineSeries2.DependentValueBinding =
new System.Windows.Data.Binding("Value2");
lineSeries2.ItemsSource = listadd();
chart.Series.Add(lineSeries2);
//chart.Series.Clear();
////延迟执行
t = new DispatcherTimer();
t.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 100 Milliseconds
//上传流
t.Tick += new EventHandler(Each_Tick);
t.Start();
//uploadStream();
}
}
void Each_Tick(object o, EventArgs sender)
{
try{
//指定上传的jsp
string uri1 = "http://10.50.20.8:7001/SLChatSaveImg.Web/imgupload.jsp";
//指定保存的文件名
string FileName = "1.jpeg";
MessageBox.Show("-- " + chart.Series.Count);
//需要上传的流
WriteableBitmap bitmap = new WriteableBitmap(chart, null);
//System.Windows.Controls.Image myImage = new System.Windows.Controls.Image();
//myImage.Source = bitmap;
//MemoryStream stream = new MemoryStream(raster);
MemoryStream stream_write = GetImageStream(bitmap);
//注意这里!!要不传不上去
byte[] bytes = stream_write.ToArray();
MemoryStream stream = new MemoryStream(bytes);
//
//中文乱码
FileName = System.Windows.Browser.HttpUtility.UrlEncode(FileName);
WebClient webclient = new WebClient();
Uri uri = new Uri(String.Format(uri1 + "?filename={0}", FileName), UriKind.Absolute);
webclient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webclient_OpenWriteCompleted);
webclient.Headers["Content-Type"] = "multipart/form-data";
//MessageBox.Show(webclient.Headers["Content-Type"]);
webclient.OpenWriteAsync(uri, "POST", stream);
//上传完成或中断时触发
webclient.WriteStreamClosed += new WriteStreamClosedEventHandler(webclient_WriteStreamClosed);
t.Stop();
}catch(Exception ee){
MessageBox.Show(ee.StackTrace);
}
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void webclient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
try
{
Stream inputStream = e.UserState as Stream;
Stream outputStream = e.Result;
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, bytesRead);
}
outputStream.Close();
inputStream.Close();
}
catch (Exception)
{
//MessageBox.Show(ee.StackTrace);
}
}
/// <summary>
/// 完成
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void webclient_WriteStreamClosed(object sender, WriteStreamClosedEventArgs e)
{
//判断写入是否有异常
if (e.Error != null)
{
MessageBox.Show("上传文件失败!");
}
else
{
MessageBox.Show("上传文件成功!");
}
}
/// <summary>
/// Get image MemoryStream from WriteableBitmap
/// </summary>
/// <param name="bitmap">WriteableBitmap</param>
/// <returns>MemoryStream</returns>
public static MemoryStream GetImageStream(WriteableBitmap bitmap)
{
byte[][,] raster = ReadRasterInformation(bitmap);
//return new MemoryStream(raster);
return EncodeRasterInformationToStreamCSharp(raster, ColorSpace.RGB);
}
/// <summary>
/// Get image MemoryStream from WriteableBitmap
/// </summary>
/// <param name="bitmap">WriteableBitmap</param>
/// <returns>MemoryStream</returns>
public static byte[] GetImageStreamJSP(WriteableBitmap bitmap)
{
byte[] raster = ReadRasterInformationJSP(bitmap);
//return new MemoryStream(raster);
return raster;
}
/// <summary>
/// Reads raster information from WriteableBitmap
/// </summary>
/// <param name="bitmap">WriteableBitmap</param>
/// <returns>Array of bytes</returns>
public static byte[] ReadRasterInformationJSP(WriteableBitmap bitmap)
{
int width = bitmap.PixelWidth;
int height = bitmap.PixelHeight;
byte[] raster = new byte[width*height];
for (int row = 0; row < height; row++)
{
for (int column = 0; column < width; column++)
{
raster[row * width + column] = (byte)bitmap.Pixels[width * row + column];
}
}
return raster;
}
/// <summary>
/// Reads raster information from WriteableBitmap
/// </summary>
/// <param name="bitmap">WriteableBitmap</param>
/// <returns>Array of bytes</returns>
public static byte[][,] ReadRasterInformation(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;
}
}
return raster;
}
/// <summary>
/// Encode raster information to MemoryStream
/// </summary>
/// <param name="raster">Raster information (Array of bytes)</param>
/// <param name="colorSpace">ColorSpace used</param>
/// <returns>MemoryStream</returns>
public static MemoryStream EncodeRasterInformationToStreamCSharp(byte[][,] raster, ColorSpace colorSpace)
{
ColorModel model = new 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);
return stream;
}
private void button3_Click(object sender, RoutedEventArgs e)
{
SaveToImage(chart);
}
/// <summary>
/// Save Visifire chart as Image
/// </summary>
/// <param name="Chart">Visifire.Charts.Chart</param>
private void SaveToImage(Chart chart)
{
try
{
WriteableBitmap bitmap = new WriteableBitmap(chart, 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())
{
MemoryStream stream = GetImageStream(bitmap);
//Get Bytes from memory stream and write into IO stream
byte[] binaryData = new Byte[stream.Length];
long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);
fs.Write(binaryData, 0, binaryData.Length);
}
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Note: Please make sure that Height and Width of the chart is set properly.");
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
}
}
然后是jsp解析流的代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.io.*" %>
<%
System.out.println("hello i am uploader");
request.setCharacterEncoding("utf-8");
String filename = request.getParameter("filename");
System.out.println("filename---"+filename);
int len = request.getContentLength();
System.out.println("len--:"+len);
byte buffer[] = new byte[len];
InputStream in = request.getInputStream();
int total = 0;
int once = 0;
while ((total < len) && (once >=0)) {
System.out.println(buffer.toString());
once = in.read(buffer,total,len);
total += once;
}
OutputStream outStream=new BufferedOutputStream(new FileOutputStream("c:\\"+filename,true));
outStream.write(buffer);
outStream.close();
%>