新建一个Silverlight应用程序,添加下面两个控件:

image控件:image1;

Button控件:Click="Button1_Click";

code-Behind代码如下:

         private void Button1_Click(object sender, RoutedEventArgs e)
{
ElementToPNG eTP = new ElementToPNG();
eTP.ShowSaveDialog(image1);
}

并添加下面三个类:

 //* -------------------------------------------------------------------------------------------------
//* 下面的三个类是处理图片导出的
//* -------------------------------------------------------------------------------------------------
# region Class ElementToPNG
public class ElementToPNG
{
public void ShowSaveDialog(UIElement elementToExport)
{
SaveFileDialog sfd = new SaveFileDialog()
{
DefaultExt = "png",
Filter = "Png files (*.png)|*.png|All files (*.*)|*.*",
FilterIndex =
}; if (sfd.ShowDialog() == true)
{
SaveAsPNG(sfd, elementToExport);
}
}
private void SaveAsPNG(SaveFileDialog sfd, UIElement elementToExport)
{
WriteableBitmap bitmap = new WriteableBitmap(elementToExport, new TranslateTransform());
EditableImage imageData = new EditableImage(bitmap.PixelWidth, bitmap.PixelHeight);
try
{
for (int y = ; y < bitmap.PixelHeight; ++y)
{
for (int x = ; x < bitmap.PixelWidth; ++x)
{
int pixel = bitmap.Pixels[bitmap.PixelWidth * y + x];
imageData.SetPixel(x, y,
(byte)((pixel >> ) & 0xFF),
(byte)((pixel >> ) & 0xFF),
(byte)(pixel & 0xFF), (byte)((pixel >> ) & 0xFF)
);
}
}
}
catch (System.Security.SecurityException)
{
throw new Exception("Cannot print images from other domains");
}
Stream pngStream = imageData.GetStream();
byte[] binaryData = new Byte[pngStream.Length];
long bytesRead = pngStream.Read(binaryData, , (int)pngStream.Length);
Stream stream = sfd.OpenFile();
stream.Write(binaryData, , binaryData.Length);
stream.Close();
}
}
# endregion # region Class EditableImage
public class EditableImage
{
private int _width = ;
private int _height = ;
private bool _init = false;
private byte[] _buffer;
private int _rowLength; public event EventHandler<EditableImageErrorEventArgs> ImageError; public EditableImage(int width, int height)
{
this.Width = width;
this.Height = height;
} public int Width
{
get
{
return _width;
}
set
{
if (_init)
{
OnImageError("Error: Cannot change Width after the EditableImage has been initialized");
}
else if ((value <= ) || (value > ))
{
OnImageError("Error: Width must be between 0 and 2047");
}
else
{
_width = value;
}
}
} public int Height
{
get
{
return _height;
}
set
{
if (_init)
{
OnImageError("Error: Cannot change Height after the EditableImage has been initialized");
}
else if ((value <= ) || (value > ))
{
OnImageError("Error: Height must be between 0 and 2047");
}
else
{
_height = value;
}
}
} public void SetPixel(int col, int row, Color color)
{
SetPixel(col, row, color.R, color.G, color.B, color.A);
} public void SetPixel(int col, int row, byte red, byte green, byte blue, byte alpha)
{
if (!_init)
{
_rowLength = _width * + ;
_buffer = new byte[_rowLength * _height]; // Initialize
for (int idx = ; idx < _height; idx++)
{
_buffer[idx * _rowLength] = ; // Filter bit
} _init = true;
} if ((col > _width) || (col < ))
{
OnImageError("Error: Column must be greater than 0 and less than the Width");
}
else if ((row > _height) || (row < ))
{
OnImageError("Error: Row must be greater than 0 and less than the Height");
} // Set the pixel
int start = _rowLength * row + col * + ;
_buffer[start] = red;
_buffer[start + ] = green;
_buffer[start + ] = blue;
_buffer[start + ] = alpha;
} public Color GetPixel(int col, int row)
{
if ((col > _width) || (col < ))
{
OnImageError("Error: Column must be greater than 0 and less than the Width");
}
else if ((row > _height) || (row < ))
{
OnImageError("Error: Row must be greater than 0 and less than the Height");
} Color color = new Color();
int _base = _rowLength * row + col + ; color.R = _buffer[_base];
color.G = _buffer[_base + ];
color.B = _buffer[_base + ];
color.A = _buffer[_base + ]; return color;
} public Stream GetStream()
{
Stream stream; if (!_init)
{
OnImageError("Error: Image has not been initialized");
stream = null;
}
else
{
stream = PngEncoder.Encode(_buffer, _width, _height);
} return stream;
} private void OnImageError(string msg)
{
if (null != ImageError)
{
EditableImageErrorEventArgs args = new EditableImageErrorEventArgs();
args.ErrorMessage = msg;
ImageError(this, args);
}
} public class EditableImageErrorEventArgs : EventArgs
{
private string _errorMessage = string.Empty; public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
} }
# endregion # region Class PngEncoder
public class PngEncoder
{
private const int _ADLER32_BASE = ;
private const int _MAXBLOCK = 0xFFFF;
private static byte[] _HEADER = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };
private static byte[] _IHDR = { (byte)'I', (byte)'H', (byte)'D', (byte)'R' };
private static byte[] _GAMA = { (byte)'g', (byte)'A', (byte)'M', (byte)'A' };
private static byte[] _IDAT = { (byte)'I', (byte)'D', (byte)'A', (byte)'T' };
private static byte[] _IEND = { (byte)'I', (byte)'E', (byte)'N', (byte)'D' };
private static byte[] _4BYTEDATA = { , , , };
private static byte[] _ARGB = { , , , , , , , , , , , , }; public static Stream Encode(byte[] data, int width, int height)
{
MemoryStream ms = new MemoryStream();
byte[] size; // Write PNG header
ms.Write(_HEADER, , _HEADER.Length); size = BitConverter.GetBytes(width);
_ARGB[] = size[]; _ARGB[] = size[]; _ARGB[] = size[]; _ARGB[] = size[]; size = BitConverter.GetBytes(height);
_ARGB[] = size[]; _ARGB[] = size[]; _ARGB[] = size[]; _ARGB[] = size[]; // Write IHDR chunk
WriteChunk(ms, _IHDR, _ARGB); // Set gamma = 1
size = BitConverter.GetBytes( * );
_4BYTEDATA[] = size[]; _4BYTEDATA[] = size[]; _4BYTEDATA[] = size[]; _4BYTEDATA[] = size[]; // Write gAMA chunk
WriteChunk(ms, _GAMA, _4BYTEDATA); // Write IDAT chunk
uint widthLength = (uint)(width * ) + ;
uint dcSize = widthLength * (uint)height; uint adler = ComputeAdler32(data);
MemoryStream comp = new MemoryStream(); // Calculate number of 64K blocks
uint rowsPerBlock = _MAXBLOCK / widthLength;
uint blockSize = rowsPerBlock * widthLength;
uint blockCount;
ushort length;
uint remainder = dcSize; if ((dcSize % blockSize) == )
{
blockCount = dcSize / blockSize;
}
else
{
blockCount = (dcSize / blockSize) + ;
} // Write headers
comp.WriteByte(0x78);
comp.WriteByte(0xDA); for (uint blocks = ; blocks < blockCount; blocks++)
{
// Write LEN
length = (ushort)((remainder < blockSize) ? remainder : blockSize); if (length == remainder)
{
comp.WriteByte(0x01);
}
else
{
comp.WriteByte(0x00);
} comp.Write(BitConverter.GetBytes(length), , ); // Write one's compliment of LEN
comp.Write(BitConverter.GetBytes((ushort)~length), , ); // Write blocks
comp.Write(data, (int)(blocks * blockSize), length); // Next block
remainder -= blockSize;
} WriteReversedBuffer(comp, BitConverter.GetBytes(adler));
comp.Seek(, SeekOrigin.Begin); byte[] dat = new byte[comp.Length];
comp.Read(dat, , (int)comp.Length); WriteChunk(ms, _IDAT, dat); // Write IEND chunk
WriteChunk(ms, _IEND, new byte[]); // Reset stream
ms.Seek(, SeekOrigin.Begin); return ms;
} private static void WriteReversedBuffer(Stream stream, byte[] data)
{
int size = data.Length;
byte[] reorder = new byte[size]; for (int idx = ; idx < size; idx++)
{
reorder[idx] = data[size - idx - ];
}
stream.Write(reorder, , size);
} private static void WriteChunk(Stream stream, byte[] type, byte[] data)
{
int idx;
int size = type.Length;
byte[] buffer = new byte[type.Length + data.Length]; // Initialize buffer
for (idx = ; idx < type.Length; idx++)
{
buffer[idx] = type[idx];
} for (idx = ; idx < data.Length; idx++)
{
buffer[idx + size] = data[idx];
} // Write length
WriteReversedBuffer(stream, BitConverter.GetBytes(data.Length)); // Write type and data
stream.Write(buffer, , buffer.Length); // Should always be 4 bytes // Compute and write the CRC
WriteReversedBuffer(stream, BitConverter.GetBytes(GetCRC(buffer)));
}
private static uint[] _crcTable = new uint[];
private static bool _crcTableComputed = false;
private static void MakeCRCTable()
{
uint c;
for (int n = ; n < ; n++)
{
c = (uint)n;
for (int k = ; k < ; k++)
{
if ((c & (0x00000001)) > )
c = 0xEDB88320 ^ (c >> );
else
c = c >> ;
}
_crcTable[n] = c;
} _crcTableComputed = true;
}
private static uint UpdateCRC(uint crc, byte[] buf, int len)
{
uint c = crc; if (!_crcTableComputed)
{
MakeCRCTable();
} for (int n = ; n < len; n++)
{
c = _crcTable[(c ^ buf[n]) & 0xFF] ^ (c >> );
} return c;
}
private static uint GetCRC(byte[] buf)
{
return UpdateCRC(0xFFFFFFFF, buf, buf.Length) ^ 0xFFFFFFFF;
}
private static uint ComputeAdler32(byte[] buf)
{
uint s1 = ;
uint s2 = ;
int length = buf.Length; for (int idx = ; idx < length; idx++)
{
s1 = (s1 + (uint)buf[idx]) % _ADLER32_BASE;
s2 = (s2 + s1) % _ADLER32_BASE;
}
return (s2 << ) + s1;
}
}
# endregion
//* -------------------------------------------------------------------------------------------------
//* -------------------------------------------------------------------------------------------------

silverlight导出图片文件的更多相关文章

  1. thinkphp3.2.3 excel导出,下载文件,包含图片

    关于导出后出错的问题 https://segmentfault.com/q/1010000005330214 https://blog.csdn.net/ohmygirl/article/detail ...

  2. winform 替换word文档中的字段(包含图片添加),生成导出PDF文件(也可是word文件)

    1.先打开你需要替换的word文档,在想要后续更换字段值的地方添加“书签”. 2.将模板文档存放在 程序的Debug文件下. 3.生成文件的按钮点击事件 代码: string templatePath ...

  3. C#向PPT文档插入图片以及导出图片

    PowerPoint演示文稿是我们日常工作中常用的办公软件之一,而图片则是PowerPoint文档的重要组成部分,那么如何向幻灯片插入图片以及导出图片呢?本文我将给大家分享如何使用一个免费版Power ...

  4. .Net导出pdf文件,C#实现pdf导出

    最近碰见个需求需要实现导出pdf文件,上网查了下代码资料总结了以下代码.可以成功的实现导出pdf文件. 在编码前需要在网上下载个itextsharp.dll,此程序集是必备的.楼主下载的是5.0版本, ...

  5. Asp.net通过模板(.dot/Html)导出Word,同时导出图片

    一.Office组件导出Word(服务器配置麻烦) 需要引用Office的DLL,在下文的附件中,不同的Offic版本用的不一样,虽然高级版本可以兼容低级的,不过,还是统一版本最好 贴上核心代码(转载 ...

  6. ReportViewer 不预览,直接导出 PDF文件

    作为笔记记着,以免以后再到处找资料 1. 在不预览的情况下导出文件 先看一个方法说明,想知道ReportViewer支持导出哪些文件类型,在Render方法说明中就有描述 // // Summary: ...

  7. FusionCharts V3图表导出图片和PDF属性说明(转)

    百闻不如一见,狠狠点击,快快下载:(演示文档有错误,不提供下载了.待新的演示文档出来.) 许多朋友说上面的DEMO用不了.fusioncharts官方的演示非常不错,就是来不及整理,各位大侠们可以研究 ...

  8. Flash 导出图片和声音

    命令文件 PolarBear_jsfl.zip Flash Professional 编辑器命令,用来导出 flash 库中的图片和声音 使用步骤: 1. 首先下载 PolarBear_jsfl.zi ...

  9. FusionChart 导出图片 功能实现(转载)

    FusionChart 导出图片 功能实现(转载) http://www.cnblogs.com/jiagoushi/archive/2013/02/05/2893468.html 题目:精美Fusi ...

随机推荐

  1. 各个JSON技术的比较(Jackson,Gson,Fastjson)的对比

    JSON技术的调研报告 一 .各个JSON技术的简介和优劣 1.json-lib json-lib最开始的也是应用最广泛的json解析工具,json-lib 不好的地方确实是依赖于很多第三方包, 包括 ...

  2. errror:[test_rig3.launch] is neither a launch file in package [svo_ros] nor is [svo_ros] a launch file name The traceback for the exception was written to the log file

    1. 打开一个终端,运行roscore 2. 打开另一个终端,运行 roslaunch svo_ros test_rig3.launch 出现errror: 忘记关键步骤了 $ cd <path ...

  3. SQL Server 数据库备份还原常用SQL语句及注意

    1.备份数据库 backup database db_name to disk='d:\db_name.bak' with format --通过使用with format可以做到覆盖任何现有的备份和 ...

  4. div中的img垂直居中的方法,最简单! 偷学来的,,,不要说我抄袭啊(*^__^*)

    让div中的img垂直居中,水平居中很简单,用text-align:center; 让div中img垂直居中的方法其实也很简单 重点是: display:table-cell;   让标签具有表格的属 ...

  5. 异常检测(Anomaly Detection)

    十五.异常检测(Anomaly Detection) 15.1 问题的动机 参考文档: 15 - 1 - Problem Motivation (8 min).mkv 在接下来的一系列视频中,我将向大 ...

  6. linux shell 重定向中的 & 符号

    写一个简单的 demo 示例 #include <stdio.h> int main() { fprintf(stdout, "stdout output\n"); f ...

  7. [SoapUI] 在SoapUI中通过Groovy脚本执行window命令杀掉进程

    //杀Excel进程 String line def p = "taskkill /F /IM EXCEL.exe".execute() def bri = new Buffere ...

  8. 我们最常见的UX设计交付成果有哪些?

    以下内容由摹客团队翻译整理,仅供学习交流,摹客iDoc是支持智能标注和切图的产品协作设计神器. 有人会好奇,用户体验(UX)设计师每天都在做些什么呢?说实话,有很多事情!作为UX专家,需要将自己的设计 ...

  9. jmeter脚本录制的两种方式

    完成一次完整的性能测试: 1.创建用户: 2.选择协议(HTTP) 3.使用工具去模拟协议操作(1.手工编写(抓包工具):2.工具自带录制) 4.运行工具进行压力测试

  10. fastcgi协议解析(nginx)

    请求NGINX ->[ {(post data) +> (NGX_HTTP_FASTCGI_STDIN)} * N +> {(environment variables) +> ...