/// <summary>
/// 地图导出功能实现模块
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SaveImage_click(object sender, RoutedEventArgs e)
{
WriteableBitmap bitmap = new WriteableBitmap(Map, null); //声明一个WriteableBitmap对象,参数Map是绘制图形的区域
if (bitmap != null)
{
SaveFileDialog saveFileDialog = new SaveFileDialog(); //调用保存文件对话框
saveFileDialog.Filter = "PDF(*.PDF)|*.pdf|PNG(*.png)|*.png|JPEG(*.jpeg)|*.jpeg|BMP(*.bmp)|*.bmp";
saveFileDialog.DefaultExt = ".pdf|.png|.jpeg|.bmp";
saveFileDialog.FilterIndex = 1;
// Save the document...
if (saveFileDialog.ShowDialog() == true)
{
Stream pdfstream = saveFileDialog.OpenFile();
if (saveFileDialog.FilterIndex == 2)
{
savePngPicToFile(bitmap, pdfstream);//调用savePngPicToFile方法保存图片,下面会介绍这个方法的实现
}
else
{
saveJpegPicToFile(bitmap, pdfstream);//调用saveJpegPicToFile方法保存图片,下面会介绍这个方法的实现
}
}
}
}
private void saveJpegPicToFile(WriteableBitmap bitmap, Stream fs) //具体保存函数实现
{
int width = bitmap.PixelWidth;
int height = bitmap.PixelHeight;
int bands = 3;
byte[][,] raster = new byte[bands][,];//用来保存bitmap中每个像素点的RGB分量的数组
for (int i = 0; i < bands; i++)
{
raster[i] = new byte[width, height];
}
for (int row = 0; row < height; row++)
{
for (int column = 0; column < width; column++)
{
int pixel = bitmap.Pixels[width * row + column];//有点问题
raster[0][column, row] = (byte)(pixel >> 16); //R
raster[1][column, row] = (byte)(pixel >> 8); //G
raster[2][column, row] = (byte)pixel; //B
}
}
FluxJpeg.Core.ColorModel model = new FluxJpeg.Core.ColorModel { colorspace = FluxJpeg.Core.ColorSpace.RGB };
FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster);
//使用jpeg编码方式
MemoryStream stream = new MemoryStream();
FluxJpeg.Core.Encoder.JpegEncoder encoder = new FluxJpeg.Core.Encoder.JpegEncoder(img, 100, stream);
encoder.Encode();
//回到stream的起始
stream.Seek(0, SeekOrigin.Begin);
//读取stream中的内容放入binaryData中,然后通过fs参数写到本地磁盘上,图片保存完成。
byte[] binaryData = new byte[stream.Length];
long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);
fs.Write(binaryData, 0, binaryData.Length);
fs.Close();
}
private void savePngPicToFile(WriteableBitmap bitmap, Stream fs) //具体保存函数实现
{
EditableImage imageData = new EditableImage(bitmap.PixelWidth, bitmap.PixelHeight);
for (int y = 0; y < bitmap.PixelHeight; ++y)
{
for (int x = 0; x < bitmap.PixelWidth; ++x)
{
int pixel = bitmap.Pixels[bitmap.PixelWidth * y + x];
imageData.SetPixel(x, y,
(byte)((pixel >> 16) & 0xFF),
(byte)((pixel >> 8) & 0xFF),
(byte)(pixel & 0xFF),
(byte)((pixel >> 24) & 0xFF)
);
}
}
//MemoryStream stream = new MemoryStream();
//回到stream的起始
// stream.Seek(0, SeekOrigin.Begin);
Stream pngStream = imageData.GetStream();
pngStream.Seek(0, SeekOrigin.Begin);
//读取stream中的内容放入binaryData中,然后通过fs参数写到本地磁盘上,图片保存完成。
byte[] binaryData = new byte[pngStream.Length];
long bytesRead = pngStream.Read(binaryData, 0, (int)pngStream.Length);
fs.Write(binaryData, 0, binaryData.Length);
fs.Close();
}
需四个文件:FJ.Core.dll;EditableImage.cs;ElementToPNG.cs;PngEncoder.cs