新建一个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. Python爬虫项目--爬取某宝男装信息

    本次爬取用到的知识点有: 1. selenium 2. pymysql 3  pyquery 正文 1. 分析目标网站 1. 打开某宝首页, 输入"男装"后点击"搜索&q ...

  2. webpack浅析---入口篇

    webpack有四个核心概念: 入口(entry) 输出(output) loader 插件(plugins) webpack-merge将环境.构建目标.运行时合并 入口: 入口起点是指webpac ...

  3. 比特币系列钱包的UTXO总结

    1.通过比特币钱包的WalletNotify配置来处理 本钱包内的交易信息的 推送.BlockNotify数据更多,不适合交易所的监听

  4. Ubuntu1.6安装Go【小白版】

    [安装golang,并配置环境变量]1.将go下载到Home目录并解压 一键解压会 自动会解压到 Home/go目录. 2.设置环境变量 nano是一种文本编辑器,也可以用其他的编辑器. 输入以下命令 ...

  5. DevExpress XPO 开发指南 简要

    最近在看devexpress   安装程序中的代码Demos ..  C:\Users\Public\Documents\DevExpress Demos 16.1\Components\WinFor ...

  6. JoyOI1035 棋盘覆盖

    原题链接 对棋盘染色,坐标和为奇数的染黑,偶数为白.这时会发现对于相同颜色的格子,是无法放置骨牌的,这样我们就将所有格子分成两类,然后根据能否放置骨牌连边,最后就是求二分图最大匹配了. 这里我是用的匈 ...

  7. sscanf 解析字符串

    test.txt中内容如下所示: eth0||192.168.0.2-192.168.0.150 eth2||192.168.0.2-192.168.0.150 想要将其中的ip地址等解析出来: #i ...

  8. java 开发微信中回调验证一直提示 解密失败处理(Java)

    微信公众号平台接入JDK6和JDK7及JDK8加解密失败处理(Java) 根据自己jdk版本编译,如jdk7或者jdk6 ,此时部署后提示报错:java.security.InvalidKeyExce ...

  9. oracle 62进制序列号

    create or replace function GetSerial62(v_lpad number default 0) return varchar2 IS v_tmp number(38,0 ...

  10. OneZero第三周第五次站立会议(2016.4.8)

    1. 时间: 15:10--15:25  共计15分钟. 2. 成员: X 夏一鸣 * 组长 (博客:http://www.cnblogs.com/xiaym896/), G 郭又铭 (博客:http ...