DotNetEden

一个普通程序员的成长记录
posts - 440, comments - 1502, trackbacks - 13, articles - 0
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

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

参考示意代码如下:

Sivlerlight端代码
        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下载有可能不能访问).

作者:张荣华
出处:http://zhangronghua.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

Feedback

#1楼  回复 引用 查看   

2011-09-13 21:14 by xiaodao      
何不直接传递 byte 给 WebSerivce。

#2楼  回复 引用 查看   

2011-09-13 22:51 by 家猫47      
@xiaodao
的确。干吗不用byte

#3楼  回复 引用   

2011-09-14 08:34 by graystar[未注册用户]
bitmap 应该可以直接处理成字节的吧,转成流,再取字节

#4楼[楼主]  回复 引用 查看   

2011-09-14 09:17 by 张荣华      
@xiaodao
@家猫47
我调用的那个WebService接口要求是String的参数啊,要不我也不用费事多转换一次了.

#5楼  回复 引用 查看   

2011-09-14 09:51 by _刘宏伟_      
不用byte原来是这样啊………………

#6楼  回复 引用 查看   

2011-09-14 17:52 by xiaodao      
那么改WebService:
读取流->字节->转字符->传递->转字节->写入流
如果直接传递字节:
读取流->字节->传递->写入流
少一步操作,编译后的程序会效率更高、更快。

#7楼[楼主]  回复 引用 查看   

2011-09-15 11:36 by 张荣华      
@xiaodao
嗯 不过没有权限改.哈...
发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 2174898 /QBi2POUkyk=