用Silverlight截取摄像头视频截图并不是什么难事。本文的范例代码详细介绍了视频截取和两种保存截图的方式:
1.使用开源的FJCore.dll 把视频流转换成Jpeg 格式,保存到本地,代码如下:
public static void EncodeJpeg(WriteableBitmap bmp,Stream dstStream) { // Init buffer in FluxJpeg format int w = bmp.PixelWidth; int h = bmp.PixelHeight; int[] p = bmp.Pixels; byte[][,] pixelsForJpeg = new byte[3][,]; // RGB colors pixelsForJpeg[0] = new byte[w,h]; pixelsForJpeg[1] = new byte[w,h]; pixelsForJpeg[2] = new byte[w,h]; // copy WriteableBitmap data into buffer for FluxJpeg int i = 0; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int color = p[i++]; pixelsForJpeg[0][x,y] = (byte)(color >> 16); // R pixelsForJpeg[1][x,y] = (byte)(color >> 8); // G pixelsForJpeg[2][x,y] = (byte)(color); // B } } //Encode Image as JPEG var jpegImage = new FluxJpeg.Core.Image(new ColorModel { colorspace = ColorSpace.RGB },pixelsForJpeg); var encoder = new JpegEncoder(jpegImage,95,dstStream); encoder.Encode(); }
//使用SaveFileDialog保存到本地 <pre name="code" class="csharp"> private void btSave_Click(object sender,RoutedEventArgs e) { if (saveFileDlg.ShowDialog().Value) { try { using (Stream dstStream = saveFileDlg.OpenFile()) { WriteableBitmap bmp = new WriteableBitmap(ViewportHost,null); EncodeJpeg(bmp,dstStream); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } }
但如何上传到服务器,并保存在数据库内,作者尝试了多种方案,由于Silverlight 在代码安全方面的诸多限制,最终选择使用把图片转换成Base64String,
使用Base64String的方法,在数据库表里建一个varchar的字段就可以保存图片数据了。
2. 通过把图片流转换成Base64String保存到服务器数据库:
实现方法:
public class Base64Convert { public static string Encode(Stream stream) { try { BinaryReader binary = new BinaryReader(stream); Byte[] imgB = binary.ReadBytes((int)stream.Length); return Convert.ToBase64String(imgB); } catch { return ""; } } public static BitmapImage Decode(string s) { byte[] imageData = Convert.FromBase64String(s); MemoryStream ms = new MemoryStream(imageData); BitmapImage tempImage = new BitmapImage(); tempImage.SetSource(ms); ms.dispose(); return tempImage; } }
private void OKButton_Click(object sender,RoutedEventArgs e) { if (_captureImage != null)//如果已经有抓拍的图像,那么可以上传 { this.txtBlog.Text = Base64Convert.Encode(SaveSnapshottoServer()); } //这时候,this.txtBlog.Text 内的Base64String 就可以保存在数据库的varchar字段内了! //如果要从数据库取回图片数据,那么就调用 // Image.source = Base64Convert.Decode("从数据库取回的string"); }
大家从上面的截图就可以看出,所截取的视频图像,已经转换成String格式,并可以保存在文本框里了。
这时候,this.txtBlog.Text 内的Base64String 就可以保存在数据库的varchar字段内了。 如果要从数据库取回图片数据,并显示在一个Image控件内,那么调用以下的方法即可: Image.source = Base64Convert.Decode("从数据库取回的string");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。