本文整理汇总了C#中System.Drawing.Imaging.Metafile.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# Metafile.Dispose方法的具体用法?C# Metafile.Dispose怎么用?C# Metafile.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Drawing.Imaging.Metafile
的用法示例。
在下文中一共展示了Metafile.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: btnInsertSelectedFiles_Click
private void btnInsertSelectedFiles_Click(object sender, EventArgs e)
{
Word.Selection selection = Globals.ThisAddIn.Application.Selection;
int objectsInWord = Globals.ThisAddIn.Application.ActiveDocument.InlineShapes.Count;
selection.Collapse(Word.WdCollapseDirection.wdCollapseStart);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToBoolean(row.Cells[0].Value) == true)
{
string emfPath = @"C:\Users\darien.shannon\Documents\_MANUALSHOPORDERS\" + jobNumber +"\\" + Convert.ToString(row.Cells[1].Value);
using (var src = new Metafile(emfPath))
using (var bmp = new Bitmap(@"C:\Users\darien.shannon\Documents\_MANUALSHOPORDERS\blank.tif"))
using (var gr = Graphics.FromImage(bmp))
{
gr.DrawImage(src, new Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.RotateFlip(RotateFlipType.Rotate90FlipNone);
imageOperations.ConvertToBlackAndWhite(bmp);
imageOperations.createPDF(bmp, @"C:\Users\darien.shannon\Documents\_MANUALSHOPORDERS\newPDF_" + jobNumber + ".pdf");
bmp.Save(@"C:\Users\darien.shannon\Documents\_MANUALSHOPORDERS\" + jobNumber + "\\" + Convert.ToString(row.Cells[1].Value).Split('.')[0] + ".tif", ImageFormat.Bmp);
msWordOperations.addSection(Word.WdOrientation.wdOrientLandscape);
selection.InlineShapes.AddOLEObject("Paint.Picture", @"C:\Users\darien.shannon\Documents\_MANUALSHOPORDERS\" + jobNumber + "\\" + Convert.ToString(row.Cells[1].Value).Split('.')[0] + ".tif", true);
objectsInWord++;
Globals.ThisAddIn.Application.ActiveDocument.InlineShapes[objectsInWord].Height = 450.0f;
Globals.ThisAddIn.Application.ActiveDocument.InlineShapes[objectsInWord].Width = 684.0f;
gr.Dispose();
bmp.Dispose();
src.Dispose();
}
System.GC.Collect();
}
}
this.Close();
}
示例2: GetInsetName
public Size GetInsetName(string p_Path, string p_FileName, string p_FileExt)
{
Size ImageSize;
Font Fnt = new Font("Arial", 8);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(1, 1);
Graphics g = Graphics.FromImage(bmp);
//*** Get maximum width of Title / Subtitle
ImageSize = g.MeasureString(m_Name, Fnt).ToSize();
ImageSize.Width = ImageSize.Width + 20;
ImageSize.Height = ImageSize.Height + 20;
bmp = new System.Drawing.Bitmap(ImageSize.Width, ImageSize.Height);
g = Graphics.FromImage(bmp);
switch (p_FileExt.ToLower())
{
case "emf":
IntPtr hRefDC = g.GetHdc();
Metafile m = new Metafile(p_Path + "\\" + p_FileName + ".emf", hRefDC);
g.ReleaseHdc(hRefDC);
Graphics gMeta = Graphics.FromImage(m);
gMeta.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
m.Dispose();
gMeta.Dispose();
break;
case "png":
g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
bmp.Save(p_Path + "\\" + p_FileName + ".png", ImageFormat.Png);
break;
case "jpg":
g.Clear(Color.White);
g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
bmp.Save(p_Path + "\\" + p_FileName + ".jpg", ImageFormat.Jpeg);
break;
case "bmp":
g.Clear(Color.White);
g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
bmp.Save(p_Path + "\\" + p_FileName + ".bmp", ImageFormat.Bmp);
break;
case "gif":
g.Clear(Color.White);
g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
bmp.Save(p_Path + "\\" + p_FileName + ".gif", ImageFormat.Gif);
break;
case "tiff":
g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
bmp.Save(p_Path + "\\" + p_FileName + ".tiff", ImageFormat.Tiff);
break;
case "ico":
g.DrawString(m_Name, Fnt, Brushes.Black, 10, 10);
bmp.Save(p_Path + "\\" + p_FileName + ".ico", ImageFormat.Icon);
break;
}
bmp.Dispose();
bmp = null;
g.Dispose();
Fnt.Dispose();
return ImageSize;
}
示例3: GetRtfImage
private static string GetRtfImage(Image _image, Control CurControl)
{
StringBuilder _rtf = null;
// Used to store the enhanced metafile
MemoryStream _stream = null;
// Used to create the metafile and draw the image
Graphics _graphics = null;
// The enhanced metafile
Metafile _metaFile = null;
// Handle to the device context used to create the metafile
IntPtr _hdc;
try
{
_rtf = new StringBuilder();
_stream = new MemoryStream();
// Get a graphics context from the RichTextBox
using (_graphics = CurControl.CreateGraphics())
{
// Get the device context from the graphics context
_hdc = _graphics.GetHdc();
// Create a new Enhanced Metafile from the device context
_metaFile = new Metafile(_stream, _hdc);
// Release the device context
_graphics.ReleaseHdc(_hdc);
}
using(_graphics = Graphics.FromImage(_metaFile))
{
// Draw the image on the Enhanced Metafile
_graphics.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height));
}
IntPtr _hEmf = _metaFile.GetHenhmetafile();
// A call to EmfToWmfBits with a null buffer return the size of the
// buffer need to store the WMF bits. Use this to get the buffer
// size.
uint _bufferSize = GdipEmfToWmfBits(_hEmf, 0, null, MM_ANISOTROPIC,
EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
// Create an array to hold the bits
byte[] _buffer = new byte[_bufferSize];
// A call to EmfToWmfBits with a valid buffer copies the bits into the
// buffer an returns the number of bits in the WMF.
uint _convertedSize = GdipEmfToWmfBits(_hEmf, _bufferSize, _buffer, MM_ANISOTROPIC,
EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
// Append the bits to the RTF string
for(int i = 0; i < _buffer.Length; ++i)
{
_rtf.Append(String.Format("{0:X2}", _buffer[i]));
}
return _rtf.ToString();
}
finally
{
if(_graphics != null)
_graphics.Dispose();
if(_metaFile != null)
_metaFile.Dispose();
if(_stream != null)
_stream.Close();
}
}
示例4: MakeMetafileStream
/// <summary>
///
/// </summary>
/// <param name="bitmap"></param>
/// <param name="shapes"></param>
/// <param name="properties"></param>
/// <param name="ic"></param>
/// <returns></returns>
public MemoryStream MakeMetafileStream(
Bitmap bitmap,
IEnumerable<BaseShape> shapes,
ImmutableArray<ShapeProperty> properties,
IImageCache ic)
{
var g = default(Graphics);
var mf = default(Metafile);
var ms = new MemoryStream();
try
{
using (g = Graphics.FromImage(bitmap))
{
var hdc = g.GetHdc();
mf = new Metafile(ms, hdc);
g.ReleaseHdc(hdc);
}
using (g = Graphics.FromImage(mf))
{
var r = new EmfRenderer(72.0 / 96.0);
r.State.ImageCache = ic;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PageUnit = GraphicsUnit.Display;
if (shapes != null)
{
foreach (var shape in shapes)
{
shape.Draw(g, r, 0, 0, properties, null);
}
}
r.ClearCache(isZooming: false);
}
}
finally
{
if (g != null)
{
g.Dispose();
}
if (mf != null)
{
mf.Dispose();
}
}
return ms;
}
示例5: SaveEnhMetaFile
/// <summary>
/// Copies the given <see cref="T:System.Drawing.Imaging.MetaFile" /> to the specified file. If the file does not exist, it will be created.
/// The given <see cref="T:System.Drawing.Imaging.MetaFile" /> is set to an invalid state inside this function.
/// </summary>
public static bool SaveEnhMetaFile(string fileName, Metafile metafile)
{
if (metafile == null) throw new ArgumentNullException("metafile");
bool result = false;
IntPtr hEmf = metafile.GetHenhmetafile();
if (hEmf != IntPtr.Zero) {
IntPtr resHEnh = CopyEnhMetaFile(hEmf, fileName);
if (resHEnh != IntPtr.Zero) {
DeleteEnhMetaFile(resHEnh);
result = true;
}
DeleteEnhMetaFile(hEmf);
metafile.Dispose();
}
return result;
}
示例6: ExportImage
protected virtual void ExportImage(string filename, string format)
{
try
{
uint pages;
Image exportImage = new Bitmap(this.worksheet.Width, this.worksheet.Height); // create export draw area
Graphics drawDestination = Graphics.FromImage(exportImage);
Graphics grph;
IntPtr ipHDC; //necessary for wmf and emf export
Metafile mf;
//EMetafile ef;
pages = GetPages(); // calculate imageBitmap page count
if (pages > 0) // something to do?
{
if (filename.LastIndexOf('.') >= (filename.Length-4)){
filename = filename.Substring(0,filename.LastIndexOf('.'));
}
for (uint i=1; i<=pages; i++){
switch (format.ToUpper()){ // identify selected format
case "BMP":
drawDestination.Clear(Color.White);
DrawPage(drawDestination,i);
exportImage.Save(filename + "_" + i + ".bmp");
break;
case "GIF":
drawDestination.Clear(Color.White);
DrawPage(drawDestination,i);
exportImage.Save(filename + "_" + i + ".gif",System.Drawing.Imaging.ImageFormat.Gif);
break;
case "JPG":
drawDestination.Clear(Color.White);
DrawPage(drawDestination,i);
exportImage.Save(filename + "_" + i + ".jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case "PNG":
drawDestination.Clear(Color.White);
DrawPage(drawDestination,i);
exportImage.Save(filename + "_" + i + ".png",System.Drawing.Imaging.ImageFormat.Png);
break;
case "WMF":
drawDestination.Clear(Color.White);
exportImage.Save(filename + "_" + i + ".wmf",System.Drawing.Imaging.ImageFormat.Wmf); // for save as wmf first empty wmf file shall be created
grph = this.CreateGraphics();
ipHDC = grph.GetHdc();
mf = new Metafile(filename + "_" + i + ".wmf", ipHDC); // open created empty wmf file
grph = Graphics.FromImage(mf);
grph.Clear(Color.White);
grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; // set image quality
grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
DrawPage(grph,i); // draw imageBitmap direct to wmf file
grph.Dispose();
mf.Dispose();
break;
case "EMF":
drawDestination.Clear(Color.White);
exportImage.Save(filename + "_" + i + ".emf",System.Drawing.Imaging.ImageFormat.Emf); // for save as emf first empty wmf file shall be created
grph = this.CreateGraphics();
ipHDC = grph.GetHdc();
mf = new Metafile(filename + "_" + i + ".emf", ipHDC); // open created empty emf file
grph = Graphics.FromImage(mf);
grph.Clear(Color.White);
grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; // set image quality
grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
DrawPage(grph,i); // draw imageBitmap direct to emf file
grph.Dispose();
mf.Dispose();
break;
}
}
}
Worksheet tmpWorksheet = new Worksheet(); // recalculate back line hights for screen output
tmpWorksheet.Width = worksheet.GetWorksheetWidth();
tmpWorksheet.Height = worksheet.GetWorksheetHeight();
tmpWorksheet.SetMargins(0,0,0,0);
drawDestination.Dispose();
exportImage.Dispose();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
示例7: saveAsImageFile
void saveAsImageFile()
{
if (File.Exists(m_strTreeFile))
{
Graphics grfx = CreateGraphics();
IntPtr ipHdc = grfx.GetHdc();
string strMetafile = createFileName("emf");
mf = new Metafile(strMetafile, ipHdc);
grfx.ReleaseHdc(ipHdc);
grfx.Dispose();
Graphics grfxMF = Graphics.FromImage(mf);
grfxMF.PageUnit = GraphicsUnit.Millimeter;
grfxMF.PageScale = .01f;
SolidBrush brush = new SolidBrush(tree.BackgroundColor);
PointF pf = new PointF(0f, 0f);
if (Environment.OSVersion.Platform == PlatformID.Win32Windows)
{ // adjust because Win98 is extra high (for some reason...)
pf.Y = grfxMF.DpiY / .254f;
}
if (tree.TrySmoothing && tree.TryPixelOffset)
tree.XSize += 6; // adjust for the pixel offset
grfxMF.FillRectangle(brush, 0, 0, tree.XSize, tree.YSize + (int)pf.Y);
tree.Draw(grfxMF, tree.LinesColor);
brush.Dispose();
grfxMF.Dispose();
string strFile;
if (m_bUseBmp)
{
strFile = createFileName("bmp");
mf.Save(strFile, ImageFormat.Bmp);
}
if (m_bUseGif)
{
strFile = createFileName("gif");
mf.Save(strFile, ImageFormat.Gif);
}
if (m_bUseJpg)
{
strFile = createFileName("jpg");
mf.Save(strFile, ImageFormat.Jpeg);
}
if (m_bUsePng)
{
strFile = createFileName("png");
mf.Save(strFile, ImageFormat.Png);
}
if (m_bUseTif)
{
strFile = createFileName("tif");
mf.Save(strFile, ImageFormat.Tiff);
}
mf.Dispose();
if (!m_bUseEmf)
File.Delete(strMetafile);
}
}
示例8: SaveAsImage
private static void SaveAsImage(IPrintable document, string path,
ImageFormat format, bool selectedOnly, bool transparent)
{
const int Margin = 20;
RectangleF areaF = document.GetPrintingArea(selectedOnly);
areaF.Offset(0.5F, 0.5F);
Rectangle area = Rectangle.FromLTRB((int) areaF.Left, (int) areaF.Top,
(int) Math.Ceiling(areaF.Right), (int) Math.Ceiling(areaF.Bottom));
if (format == ImageFormat.Emf) // Save to metafile
{
Graphics metaG = control.CreateGraphics();
IntPtr hc = metaG.GetHdc();
Graphics g = null;
try
{
// Set drawing parameters
Metafile meta = new Metafile(path, hc);
g = Graphics.FromImage(meta);
g.SmoothingMode = SmoothingMode.HighQuality;
if (DiagramEditor.Settings.Default.UseClearTypeForImages)
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
else
g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
g.TranslateTransform(-area.Left, -area.Top);
// Draw image
IGraphics graphics = new GdiGraphics(g);
document.Print(graphics, selectedOnly, Style.CurrentStyle);
meta.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(
string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
Strings.ErrorsReason, ex.Message),
Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
metaG.ReleaseHdc();
metaG.Dispose();
if (g != null)
g.Dispose();
}
}
else // Save to rastered image
{
int width = area.Width + Margin * 2;
int height = area.Height + Margin * 2;
PixelFormat pixelFormat;
if (transparent)
pixelFormat = PixelFormat.Format32bppArgb;
else
pixelFormat = PixelFormat.Format24bppRgb;
using (Bitmap image = new Bitmap(width, height, pixelFormat))
using (Graphics g = Graphics.FromImage(image))
{
// Set drawing parameters
g.SmoothingMode = SmoothingMode.HighQuality;
if (DiagramEditor.Settings.Default.UseClearTypeForImages && !transparent)
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
else
g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
g.TranslateTransform(Margin - area.Left, Margin - area.Top);
// Draw image
if (!transparent)
g.Clear(Style.CurrentStyle.BackgroundColor);
IGraphics graphics = new GdiGraphics(g);
document.Print(graphics, selectedOnly, Style.CurrentStyle);
try
{
image.Save(path, format);
}
catch (Exception ex)
{
MessageBox.Show(
string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
Strings.ErrorsReason, ex.Message),
Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
示例9: AddPictire
void AddPictire(Plan plan, surfacesSurfaceLayerElementsElement innerElement, ref int pictureIndex)
{
try
{
if (innerElement.picture == null)
return;
foreach (var innerPicture in innerElement.picture)
{
if (string.IsNullOrEmpty(innerPicture.idx))
innerPicture.idx = pictureIndex++.ToString();
var picturesDirectory = GetPicturesDirectory();
if (picturesDirectory == null)
continue;
var directoryInfo = new DirectoryInfo(picturesDirectory + "\\Sample" + innerPicture.idx + "." + innerPicture.ext);
if (File.Exists(directoryInfo.FullName) == false)
continue;
if (innerPicture.ext == "emf")
{
var metafile = new Metafile(directoryInfo.FullName);
innerPicture.ext = "bmp";
directoryInfo = new DirectoryInfo(picturesDirectory + "\\Sample" + innerPicture.idx + "." + innerPicture.ext);
metafile.Save(directoryInfo.FullName, ImageFormat.Bmp);
metafile.Dispose();
}
var guid = ServiceFactoryBase.ContentService.AddContent(directoryInfo.FullName);
var elementRectanglePicture = new ElementRectangle()
{
Left = Parse(innerElement.rect[0].left),
Top = Parse(innerElement.rect[0].top),
Height = Parse(innerElement.rect[0].bottom) - Parse(innerElement.rect[0].top),
Width = Parse(innerElement.rect[0].right) - Parse(innerElement.rect[0].left),
};
if ((elementRectanglePicture.Left == 0) && (elementRectanglePicture.Top == 0) && (elementRectanglePicture.Width == plan.Width) && (elementRectanglePicture.Height == plan.Height))
{
plan.BackgroundImageSource = guid;
plan.BackgroundSourceName = directoryInfo.FullName;
}
else
{
elementRectanglePicture.BackgroundImageSource = guid;
elementRectanglePicture.BackgroundSourceName = directoryInfo.FullName;
plan.ElementRectangles.Add(elementRectanglePicture);
}
}
}
catch (Exception e)
{
Logger.Error(e, "ConfigurationConverter.AddPictire");
}
}
示例10: WorldTransforms
public void WorldTransforms ()
{
Metafile mf;
using (Bitmap bmp = new Bitmap (100, 100, PixelFormat.Format32bppArgb)) {
using (Graphics g = Graphics.FromImage (bmp)) {
IntPtr hdc = g.GetHdc ();
try {
mf = new Metafile (hdc, EmfType.EmfPlusOnly);
}
finally {
g.ReleaseHdc (hdc);
}
}
using (Graphics g = Graphics.FromImage (mf)) {
Assert.IsTrue (g.Transform.IsIdentity, "Initial/IsIdentity");
g.ScaleTransform (2f, 0.5f);
Assert.IsFalse (g.Transform.IsIdentity, "Scale/IsIdentity");
g.RotateTransform (90);
g.TranslateTransform (-2, 2);
Matrix m = g.Transform;
g.MultiplyTransform (m);
// check
float[] elements = g.Transform.Elements;
Assert.AreEqual (-1f, elements[0], 0.00001f, "a0");
Assert.AreEqual (0f, elements[1], 0.00001f, "a1");
Assert.AreEqual (0f, elements[2], 0.00001f, "a2");
Assert.AreEqual (-1f, elements[3], 0.00001f, "a3");
Assert.AreEqual (-2f, elements[4], 0.00001f, "a4");
Assert.AreEqual (-3f, elements[5], 0.00001f, "a5");
g.Transform = m;
elements = g.Transform.Elements;
Assert.AreEqual (0f, elements[0], 0.00001f, "b0");
Assert.AreEqual (0.5f, elements[1], 0.00001f, "b1");
Assert.AreEqual (-2f, elements[2], 0.00001f, "b2");
Assert.AreEqual (0f, elements[3], 0.00001f, "b3");
Assert.AreEqual (-4f, elements[4], 0.00001f, "b4");
Assert.AreEqual (-1f, elements[5], 0.00001f, "b5");
g.ResetTransform ();
Assert.IsTrue (g.Transform.IsIdentity, "Reset/IsIdentity");
}
mf.Dispose ();
}
}
示例11: Measure
public void Measure ()
{
if (test_font == null)
Assert.Ignore ("No font family could be found.");
Metafile mf;
using (Bitmap bmp = new Bitmap (100, 100, PixelFormat.Format32bppArgb)) {
using (Graphics g = Graphics.FromImage (bmp)) {
IntPtr hdc = g.GetHdc ();
try {
mf = new Metafile (hdc, EmfType.EmfPlusOnly);
}
finally {
g.ReleaseHdc (hdc);
}
}
using (Graphics g = Graphics.FromImage (mf)) {
string text = "this\nis a test";
CharacterRange[] ranges = new CharacterRange[2];
ranges[0] = new CharacterRange (0, 5);
ranges[1] = new CharacterRange (5, 9);
SizeF size = g.MeasureString (text, test_font);
Assert.IsFalse (size.IsEmpty, "MeasureString");
StringFormat sf = new StringFormat ();
sf.FormatFlags = StringFormatFlags.NoClip;
sf.SetMeasurableCharacterRanges (ranges);
RectangleF rect = new RectangleF (0, 0, size.Width, size.Height);
Region[] region = g.MeasureCharacterRanges (text, test_font, rect, sf);
Assert.AreEqual (2, region.Length, "MeasureCharacterRanges");
}
mf.Dispose ();
}
}
示例12: CreateFilename
private void CreateFilename (EmfType type, bool single)
{
string name = String.Format ("{0}-{1}.emf", type, single ? "Single" : "Multiple");
string filename = Path.Combine (Path.GetTempPath (), name);
Metafile mf;
using (Bitmap bmp = new Bitmap (100, 100, PixelFormat.Format32bppArgb)) {
using (Graphics g = Graphics.FromImage (bmp)) {
IntPtr hdc = g.GetHdc ();
try {
mf = new Metafile (filename, hdc, type);
Assert.AreEqual (0, new FileInfo (filename).Length, "Empty");
}
finally {
g.ReleaseHdc (hdc);
}
}
long size = 0;
using (Graphics g = Graphics.FromImage (mf)) {
g.FillRectangle (Brushes.BlueViolet, 10, 10, 80, 80);
size = new FileInfo (filename).Length;
Assert.AreEqual (0, size, "Still-Empty");
}
// FIXME / doesn't work on mono yet
// size = new FileInfo (filename).Length;
// Assert.IsTrue (size > 0, "Non-Empty/GraphicsDisposed");
if (!single) {
// can we append stuff ?
using (Graphics g = Graphics.FromImage (mf)) {
g.DrawRectangle (Pens.Azure, 10, 10, 80, 80);
// happily no :)
}
}
mf.Dispose ();
Assert.AreEqual (size, new FileInfo (filename).Length, "Non-Empty/MetafileDisposed");
}
}
示例13: RenderAsEnhancedMetafileToStream
//.........这里部分代码省略.........
// this accounts for the fact, that if
double deviceResolution = sourceDpiResolution / outputScalingFactor;
// then the number of pixels of the device is simple the device size in inch times the device resolution
int devicePixelsX = (int)Math.Round(deviceSizeInch * deviceResolution);
int devicePixelsY = (int)Math.Round(deviceSizeInch * deviceResolution);
// device size in millimeter. Because of the choice of the device size (see above) there should be no rounding errors here
int deviceSizeXMillimeter = (deviceSizeInch * 254) / 10;
int deviceSizeYMillimeter = (deviceSizeInch * 254) / 10;
// device size in micrometer
int deviceSizeXMicrometer = deviceSizeInch * 25400;
int deviceSizeYMicrometer = deviceSizeInch * 25400;
// bounds of the graphic in pixels. Because it is in pixels, it is calculated with the unscaled size of the document and the sourceDpiResolution
int graphicBoundsLeft_Pixels = 0;
int graphicBoundsTop_Pixels = 0;
int graphicBoundsWidth_Pixels = (int)Math.Ceiling(sourceDpiResolution * docSize.X / 72);
int graphicBoundsHeight_Pixels = (int)Math.Ceiling(sourceDpiResolution * docSize.Y / 72);
// position and size of the bounding box. Please not that the bounds are scaled with the outputScalingFactor
int boundingBoxLeft_HIMETRIC = 0;
int boundingBoxTop_HIMETRIC = 0;
int boundingBoxWidth_HIMETRIC = (int)Math.Ceiling(scaledDocSize.X * 2540.0 / 72);
int boundingBoxHeight_HIMETRIC = (int)Math.Ceiling(scaledDocSize.Y * 2540.0 / 72);
Metafile metafile;
using (var helperbitmap = new System.Drawing.Bitmap(4, 4, PixelFormat.Format32bppArgb))
{
using (Graphics grfxReference = Graphics.FromImage(helperbitmap))
{
IntPtr deviceContextHandle = grfxReference.GetHdc();
metafile = new Metafile(
stream,
deviceContextHandle,
new RectangleF(boundingBoxLeft_HIMETRIC, boundingBoxTop_HIMETRIC, boundingBoxWidth_HIMETRIC, boundingBoxHeight_HIMETRIC),
MetafileFrameUnit.GdiCompatible,
EmfType.EmfPlusDual); // EmfOnly is working with PolyLines with more than 8125 Points, but can not handle transparencies // EmfPlusDual and EmfPlusOnly: there is no display of polylines with more than 8125 points, although the polyline seems embedded in the EMF. // EmfPlusOnly can not be converted to WMF
grfxReference.ReleaseHdc();
}
}
using (Graphics grfxMetafile = Graphics.FromImage(metafile))
{
// Set everything to high quality
grfxMetafile.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
grfxMetafile.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
// 2014-10-10 Setting InterpolationMode to HighQualityBicubic and PixelOffsetMode to HighQuality
// causes problems when rendering small bitmaps (at a large magnification, for instance the density image legend):
// the resulting image seems a litte soft, the colors somehow distorted, so I decided not to use them here any more
//grfxMetafile.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
//grfxMetafile.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
grfxMetafile.PageUnit = GraphicsUnit.Pixel; // Attention: always use pixels here. Any other choice will cause problems in some programs (see remarks above).
grfxMetafile.PageScale = (float)(sourceDpiResolution / 72.0); // because our choice of GraphicsUnit is pixels, at the resolution of 72 dpi one point is one pixel. At a higher resolution, one point is more than one pixel.
grfxMetafile.SetClip(new RectangleF(0, 0, (float)docSize.X, (float)docSize.Y));
renderingProc(grfxMetafile);
}
stream.Flush();
// we have to patch the resulting metafile stream with the parameters of the graphics and the device
stream.Position = 0x04;
var buf4 = new byte[4];
stream.Read(buf4, 0, 4);
int headerSize = BitConverter.ToInt32(buf4, 0); // Read the header size to make sure that Metafile header extension 2 is present
// At position 0x08 there are the bounds of the graphic (not the bounding box, but the box for all the graphical elements)
stream.Position = 0x08;
stream.Write(BitConverter.GetBytes(graphicBoundsLeft_Pixels), 0, 4);
stream.Write(BitConverter.GetBytes(graphicBoundsTop_Pixels), 0, 4);
stream.Write(BitConverter.GetBytes(graphicBoundsWidth_Pixels), 0, 4);
stream.Write(BitConverter.GetBytes(graphicBoundsHeight_Pixels), 0, 4);
// At position 0x48 the device parameters are located: here the number of pixels of the device
stream.Position = 0x48;
stream.Write(BitConverter.GetBytes(devicePixelsX), 0, 4); // the number of pixels of the device X
stream.Write(BitConverter.GetBytes(devicePixelsY), 0, 4); // the number of pixels of the device Y
stream.Write(BitConverter.GetBytes(deviceSizeXMillimeter), 0, 4); // size X of the device in millimeter
stream.Write(BitConverter.GetBytes(deviceSizeYMillimeter), 0, 4); // size Y of the device in millimeter
if (headerSize >= (0x64 + 0x08))
{
stream.Position = 0x64;
stream.Write(BitConverter.GetBytes(deviceSizeXMicrometer), 0, 4); // size X of the device in micrometer
stream.Write(BitConverter.GetBytes(deviceSizeYMicrometer), 0, 4); // size Y of the device in micrometer
}
stream.Flush();
stream.Position = 0;
metafile.Dispose(); // we can safely dispose this metafile, because stream and metafile are independent of each other, and only the stream is patched
}
示例14: GenerateImageRtf
private string GenerateImageRtf(Image image)
{
MemoryStream metaFileStream = null;
Graphics graphics = null;
Metafile metaFile = null;
try
{
StringBuilder stringBuilder = new StringBuilder();
metaFileStream = new MemoryStream();
using (graphics = this.CreateGraphics())
{
IntPtr hdc = graphics.GetHdc();
metaFile = new Metafile(metaFileStream, hdc);
graphics.ReleaseHdc(hdc);
}
using (graphics = Graphics.FromImage(metaFile))
{
graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height));
}
IntPtr hMetaFile = metaFile.GetHenhmetafile();
// get size (buller = null)
uint bufferSize = GdipEmfToWmfBits(hMetaFile, 0, null, MM_ANISOTROPIC,
EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
byte[] buffer = new byte[bufferSize];
// do copy (buffer != null, return ignored)
GdipEmfToWmfBits(hMetaFile, bufferSize, buffer, MM_ANISOTROPIC,
EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
stringBuilder.Append(BitConverter.ToString(buffer).Replace("-", ""));
return stringBuilder.ToString();
}
finally
{
if (graphics != null)
graphics.Dispose();
if (metaFile != null)
metaFile.Dispose();
if (metaFileStream != null)
metaFileStream.Close();
}
}
示例15: ExportImage
private void ExportImage(string filename, string format)
{
uint pages;
Image exportImage = new Bitmap(this.worksheet.Width, this.worksheet.Height); // create export draw area
Bitmap b= new Bitmap(100,100);
Graphics drawDestination = Graphics.FromImage(exportImage);
Graphics grph;
IntPtr ipHDC; //necessary for wmf and emf export
Metafile mf;
generator.CalcLineHights(drawDestination, worksheet, MSCItem.ItemFont);
pages = generator.GetPages(worksheet.GetWorksheetHeight()); // calculate imageBitmap page count
if (pages > 0) // something to do?
{
if (filename.LastIndexOf('.') >= (filename.Length-4)){
filename = filename.Substring(0,filename.LastIndexOf('.'));
}
uint i = 1;
string filenameSuffix = "";
// if (singlePage)
// i = pages = 0;
for (; i<=pages; i++){
if (i > 0)
filenameSuffix = "_" + i.ToString();
if (Output.AutosizeOutputHeight){
uint index = i;
if (index > 0)
index--;
worksheet.SetWorksheetHeight((int)generator.PageHeights[index]); // correct height for export
exportImage = new Bitmap(this.worksheet.Width, this.worksheet.Height);
drawDestination = Graphics.FromImage(exportImage);
}
if (Output.AutosizeOutputWidth){
worksheet.SetWorksheetWidth((int)generator.AutoWidth);
}
switch (format.ToUpper()){ // identify selected format
case "BMP":
drawDestination.Clear(Color.White);
generator.CalcOffsets(drawDestination, worksheet);
generator.DrawPage(drawDestination,worksheet, i);
exportImage.Save(filename + filenameSuffix + ".bmp");
break;
case "GIF":
drawDestination.Clear(Color.White);
generator.CalcOffsets(drawDestination, worksheet);
generator.DrawPage(drawDestination,worksheet, i);
exportImage.Save(filename + filenameSuffix + ".gif",System.Drawing.Imaging.ImageFormat.Gif);
break;
case "JPG":
drawDestination.Clear(Color.White);
generator.CalcOffsets(drawDestination, worksheet);
generator.DrawPage(drawDestination,worksheet, i);
exportImage.Save(filename + filenameSuffix + ".jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case "PNG":
drawDestination.Clear(Color.White);
generator.CalcOffsets(drawDestination, worksheet);
generator.DrawPage(drawDestination,worksheet, i);
exportImage.Save(filename + filenameSuffix + ".png",System.Drawing.Imaging.ImageFormat.Png);
break;
case "WMF":
drawDestination.Clear(Color.White);
exportImage.Save(filename + filenameSuffix + ".wmf",System.Drawing.Imaging.ImageFormat.Wmf); // for save as wmf first empty wmf file shall be created
grph = Graphics.FromImage(b);
ipHDC = grph.GetHdc();
mf = new Metafile(filename + filenameSuffix + ".wmf", ipHDC); // open created empty wmf file
grph = Graphics.FromImage(mf);
grph.Clear(Color.White);
grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; // set image quality
grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
generator.CalcOffsets(grph, worksheet);
generator.DrawPage(grph,worksheet, i);
grph.Dispose();
mf.Dispose();
break;
case "EMF":
System.IO.FileStream st= new FileStream(filename + "_" + i + ".emf",FileMode.Create);
drawDestination.Clear(Color.White);
grph = Graphics.FromImage(b);
ipHDC = grph.GetHdc();
mf = new Metafile(st,ipHDC);
grph = Graphics.FromImage(mf);
grph.Clear(Color.White);
grph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; // set image quality
grph.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
generator.CalcOffsets(grph, worksheet);
generator.DrawPage(grph,worksheet, i);
grph.Dispose();
mf.Dispose();
break;
}
if (verbose) {
if (singlePage)
Console.WriteLine("Diagram created.");
else
Console.WriteLine("Page " + i.ToString()+ " created.");
}
}
}
drawDestination.Dispose();
//.........这里部分代码省略.........