首页  ·  知识 ·  移动开发
Silverlight程序中实现客户端截图发送到服务端
张荣华     Wphone  编辑:dezai   图片来源:网络
有时在Silverlight项目里我们需要让用户在Silverlight程序中点击截图按钮并将用户截取到的图片上传到服务器端进行处理,比如发送到FTP或

有时在Silverlight项目里我们需要让用户在Silverlight程序中点击截图按钮并将用户截取到的图片上传到服务器端进行处理,比如发送到FTP或者存储到数据库中. 但是由于WebService不能传递Image类型的参数,所以我们就需要先将用户截取到的图片编码成一个String传递到WebService端,然后再在WebService端解码成Image并进行处理.

参考示意代码如下:

public static string SaveScreenToString()
{
var bitmap
= new WriteableBitmap(Application.Current.RootVisual, null);

//Convert the Image to pass into FJCore
int width = bitmap.PixelWidth;
int height = bitmap.PixelHeight;
int bands = 3;

var 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;
}
}

var model
= new ColorModel { colorspace = ColorSpace.RGB };

var img
= new Image(model, raster);

//Encode the Image as a JPEG
var stream = new MemoryStream();
var encoder
= new JpegEncoder(img, 100, stream);

encoder.Encode();

//Move back to the start of the stream
stream.Seek(0, SeekOrigin.Begin);

//Get the Bytes and write them to the stream
var binaryData = new Byte[stream.Length];
long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);

return Convert.ToBase64String(binaryData);

}

Web Service端代码

var binaryData = Convert.FromBase64String(imageStreamString);
var imageFilePath
= Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath) + "/Temp/snap.jpg";
if(File.Exists(imageFilePath))
{
File.Delete(imageFilePath);
}
var stream
= new System.IO.FileStream(imageFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
stream.Write(binaryData,
0, binaryData.Length);
stream.Close();

PS: 代码中用到了FJ.Core.Dll,你可以从Google上下载这个文件,也可以从我的Dropbox里下载(由于GFW的原因Dropbox下载有可能不能访问).

 

本文作者:张荣华 来源:网络
CIO之家 www.ciozj.com 微信公众号:imciow
    >>频道首页  >>网站首页   纠错  >>投诉
版权声明:CIO之家尊重行业规范,每篇文章都注明有明确的作者和来源;CIO之家的原创文章,请转载时务必注明文章作者和来源;
延伸阅读
也许感兴趣的
我们推荐的
主题最新
看看其它的