需求:從播放器上截取出當前幀,提交到伺服器/或吐給javascript
1、從當前的MediaElement上建立WriteableBitmap
WriteableBitmap bitmap = new WriteableBitmap(this.Player, null);
2、從WriteableBitmap編碼成jpg格式
public static void SavePicToStream(WriteableBitmap bitmap, Stream stream) { int width = bitmap.PixelWidth; int height = bitmap.PixelHeight; int bands = 3; byte[][,] raster = new byte[bands][,]; //用來儲存bitmap中每個像素點的RGB分量的數組 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); //R raster[1][column, row] = (byte)(pixel >> 8); //G raster[2][column, row] = (byte)pixel; //B } } FluxJpeg.Core.ColorModel model = new FluxJpeg.Core.ColorModel { colorspace = FluxJpeg.Core.ColorSpace.RGB }; FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster); FluxJpeg.Core.Encoder.JpegEncoder encoder = new FluxJpeg.Core.Encoder.JpegEncoder(img, 100, stream); encoder.Encode(); }
3、轉化為base64編碼傳輸
public string GetCurrentImageBase64String() { var stream = new MemoryStream(); Tools.SavePicToStream(this.GetCurrentImage(), stream); stream.Seek(0, SeekOrigin.Begin); var binaryData = new Byte[stream.Length]; long bytesRead = stream.Read(binaryData, 0, (int)stream.Length); string t = Convert.ToBase64String(binaryData); return t; }
注意:視頻檔案和XAP必須在同一個域,否則將出現WriteableBitmap的Pixels受保護,無法讀。(出於著作權保護的原因)
微軟MSDN給出的解釋如下:
受保護的內容
如果使用跨域內容構造 WriteableBitmap,則 WriteableBitmap 類具有安全模式,該模式限制對 Pixels 數組的訪問。 例如,使用引用來自另一個域的 URL 的BitmapImage 構造的 WriteableBitmap 不允許訪問其 Pixels 數組。 該限制擴充到任何為設定其部分或所有內容而使用 URL 派生屬性的 UI 元素。 具體而言,此限制適用於“從 MediaElement 抓取正在啟動並執行視訊框架”方案。 如果 MediaElement.Source 引用另一個域中的視頻檔案,那麼通過引用 MediaElement 作為元素源建立的 WriteableBitmap 限制對 Pixels 數組的訪問。
即使建立自受保護的內容,也仍可以訪問 WriteableBitmap 的 PixelHeight 和 PixelWidth 屬性。 此資訊可用於確定內容的固有大小,例如用於保留其大小調整到源的 MediaElement。