您的位置:首页 - .NET
Silverlight将Canvas截屏保存为图片
在Grid中插入一个Canvas控件,名称设为canvas_keleyi_com,让后向canvas_keleyi_com中添加图片或其他内容,调用SaveTheImg()就可以了,记得Canvas的内容需要是同个域名下的否则会报错:"WriteableBitmap 已对内容进行保护。不允许访问像素。"

以下是实现功能的方法
private WriteableBitmap _bitmap;
/// <summary>
/// 保存图片
/// </summary>
private void SaveTheImg()
{
_bitmap = new WriteableBitmap(canvas_keleyi_com, null);
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "PNG Files (*.png)|*.png|All Files (*.*)|*.*";
sfd.DefaultExt = ".png";
sfd.FilterIndex = 1;

if ((bool)sfd.ShowDialog())
{
using (Stream fs = sfd.OpenFile())
{
int width = _bitmap.PixelWidth;
int height = _bitmap.PixelHeight;

EditableImage ei = new EditableImage(width, height);

for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int pixel = _bitmap.Pixels[(i * width) + j];
ei.SetPixel(j, i,
(byte)((pixel >> 16) & 0xFF),
(byte)((pixel >> 8) & 0xFF),
(byte)(pixel & 0xFF),
(byte)((pixel >> 24) & 0xFF)
);
}
}
//获取流
Stream png = ei.GetStream();
int len = (int)png.Length;
byte[] bytes = new byte[len];
png.Read(bytes, 0, len);
fs.Write(bytes, 0, len);
}
}
}


private static bool SaveBinaryFile(WebResponse response, string savePath)
{
bool value = false;
byte[] buffer = new byte[1024];
Stream outStream = null;
Stream inStream = null;
try
{
if (File.Exists(savePath)) File.Delete(savePath);
outStream = System.IO.File.Create(savePath);
inStream = response.GetResponseStream();
int l;
do
{
l = inStream.Read(buffer, 0, buffer.Length);
if (l > 0) outStream.Write(buffer, 0, l);
} while (l > 0);
value = true;
}
finally
{
if (outStream != null) outStream.Close();
if (inStream != null) inStream.Close();
}
return value;
}

}
本站导航
相关文章
柯乐义 Copyright© keleyi.com