新建一个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. 27-java String 之间比较的幺蛾子

    仔细看啊, 他有双引号啊!!!!

  2. supervisor安装、使用详解

    supervisor是用python写的一个进程管理工具,用来启动,重启,关闭进程. 1 supervisor的安装 pip install supervisor 2 supervisor的配置文件( ...

  3. YII2中如何自定义全局函数

    有些时候我们需要自定义一些全局函数来完成我们的工作. 方法一: 直接写在入口文件处 <?php // comment out the following two lines when deplo ...

  4. linux操作系统-设置静态ip

    在使用linux虚拟机的时候因为经常有关机的需求,然后重新开机后可能面临这上一次获取的ip被改变,在这里我分享一下在linux 下设置静态ip的经验 1.查看路由状态 [root@localhost ...

  5. Linux_(2)基本命令(下)

    六.文件搜索命令11 :which功能描述:显示系统命令所在目录命令所在路径:/usr/bin/which执行权限:所有用户语法:which [命令名称]范例:$ which ls 12 :find功 ...

  6. mybatis入门--#{}和${}的区别

    我们知道,在mybatis中,sql语句是需要我们自己写的.跟在普通的sql不一样的是,我们在使用mybatis框架的时候,使用的占位符不是 ? 而是 #{} 有时候还会出现这个符号 ${} 这些符号 ...

  7. IDEA 调整 VM 配置文件(64位)

    64 位操作系统中 8G 内存以下的机子或是静态页面开发者是无需修改的. 64 位操作系统且内存大于 8G 的, 如果你是开发大型项目. Java 项目或是 Android 项目,建议进行修改 . 1 ...

  8. BZOJ 4521 [CQOI2016]手机号码 - 数位DP

    Description 在$[L, R]$找出有几个数满足两个条件 : 1 : 不同时含有$4$ 和 $8$ 2 : 至少有$3$个相邻的数相同 Solution 非常容易的数位DP, $pos$ 为 ...

  9. imaplib.error: command: SEARCH => got more than 10000 bytes

    imaplib.error: command: SEARCH => got more than 10000 bytes 使用IMAPLIB进行标记邮件状态的时候,在 typ,data=M.sea ...

  10. vim自动添加tags、cscope

    每次打开一个工程都需要重新添加tags.cscope,很不方便,网上找了一下. 将其添加到 ~/.vimrc 中之后,打开 vim 就会自动搜索当前路径下的tags.cscope添加进去. 自动添加 ...