If I call the following method twice, it works, but exporting the same image twice every time i need an image is not an option. Most of the time i will be using an MXD pointing to local data, and doubling the already long export time is not exactly ideal.
private Bitmap GetImageFromJpegExporter(tagRECT rect, CancelTracker trackCancel)
{
string filename = Guid.NewGuid().ToString();
try
{
tagRECT exportRECT = _mapDocument.ActiveView.ExportFrame;
//Create a new envelope object and populate it with the values from exportRECT.
// We need to do this because the exporter object requires an envelope object
// instead of a tagRECT structure.
IEnvelope pPixelBoundsEnv = new EnvelopeClass();
pPixelBoundsEnv.PutCoords(exportRECT.left, exportRECT.top, exportRECT.right, exportRECT.bottom);
IExport export = new ExportJPEGClass
{
Resolution = 96,
ExportFileName = filename,
PixelBounds = pPixelBoundsEnv
};
Stopwatch watch = new Stopwatch();
watch.Start();
int hwnd = export.StartExporting();
_mapDocument.ActiveView.Output(hwnd, 96, ref rect, _mapDocument.ActiveView.Extent, trackCancel);
export.FinishExporting();
export.Cleanup();
watch.Stop();
Trace.WriteLine("Export took " + watch.ElapsedMilliseconds + " ms");
Bitmap fromFileBitmap = new Bitmap(filename);
// Copy fromFileBitmap because it keeps a lock on the file
Bitmap returnBitmap = new Bitmap(fromFileBitmap);
fromFileBitmap.Dispose();
return returnBitmap;
}
finally
{
if(File.Exists(filename))
{
try
{
File.Delete(filename);
}
catch (Exception)
{
}
}
}
}