新建一个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. [ERR] Node 192.168.25.135:7001 is not empty. Either the node already knows other nodes (check with CLUSTER NODES) or contains some key in database 0.

    原文链接:https://www.cnblogs.com/huxinga/p/6644226.html 解决办法:将redis全部shutdown 将每个节点下aof.rdb.nodes.conf本地 ...

  2. Linux磁盘分区与文件系统

    一 Linux磁盘分区与文件系统 在Linux中常见的操作系统有:ext2 ext3 ext4 xfs btrfs reiserfs等文件系统的作用主要是明确磁盘或分区上的文件存储方法以及数据结构,L ...

  3. mysql导入慢解决方法

    [mysqldump]max_allowed_packet = 512M [mysqld] interactive_timeout = 120 innodb_change_buffering=alli ...

  4. 移动端 input 输入框实现自带键盘“搜索“功能并修改X

    主要利用html5的,input[type=search]属性来实现,此时input和type=text外观和功能没啥区别: html代码入下: <form action="" ...

  5. 使用独立的log4net.config文件配置log4net,将日志记录到Mysql数据库【原创】

    开发环境: VS2013, Asp.Net MVC 4.0, .Net Framework 4.0, Log4net 1.2.13.0, Mysql.Data.dll,6.8.3.0 设置步骤: 1. ...

  6. 利用七牛存储7天远程自动备份LINUX服务器

    受服务器空间制约,我们不可能在VPS上每天都备份一份新的网站数据,一是没必要,二是占空间.我们折中一下,采用星期命名,每次备份将覆盖上星期同一天的文件.从而只备份7份数据,不至于占用特别大的空间. 如 ...

  7. Luogu 3421 [POI2005]SKO-Knights - Exgcd

    Description 给出一个骑士的 $N$种 中行走的方式 $(a_i, b_i)$, 可以使骑士的坐标$(-a,-b)$或$(+a,+b)$. 我们需要找出 第二个骑士的 两种行走方式 $(c_ ...

  8. 20172325 2018-2019-2 《Java程序设计》第五周学习总结

    20172325 2018-2019-2 <Java程序设计>第五周学习总结 教材学习内容总结 本次学习第九章内容,主要学习查找和排序. 查找 查找的定义:是一个过程,即在某个项目组中寻找 ...

  9. 04. pt-deadlock-logger

    死锁:是指两个或则多个事务在同一个资源上相互占用,并请求锁定对方占用的资源,而导致恶性循环的现象:当产生死锁的时候,MySQL会回滚一个小事务的SQL,确保另一个完成.上面是死锁的概念,而在MySQL ...

  10. 【Linux】开机自动启动脚本

    Linux下(以RedHat为范本)添加开机开机自动启动脚本有两种方式; 本例系统:Linux(CentOS 7.2) 方法一 使用 /etc/rc.d/rc.local,自动启动脚本 #!/bin/ ...