Skip to main content

How to export CAD files to JPEG with a specified DPI?

  1. Add a new button. Name it ExportBMP. Then create the ExportBMP_Click function to export a CAD file to BMP by click.
private void ExportBMP_Click(object sender, EventArgs e){
  1. Use the ShowDialog method to load a CAD file from the dialog window. Create a new instance of the CADImage class.
  if ((openFileDialog1.ShowDialog() != DialogResult.OK)) return;
CADImage vDrawing = CADImage.CreateImageByExtension(openFileDialog1.FileName);
vDrawing.LoadFromFile(openFileDialog1.FileName);
Tip

We recommend creating a new drawing object using CreateImageByExtension in case of importing from an existing file or stream.

  1. Declare the local variables vHeight and vWidth of Double. Don't forget to check the vHeight value for exceeding the permissible limits. Finally, create an instance of the Bitmap class and assign values vWidth and vHeight to the Width and Height properties.
  Double vHeight = 1;
Double vWidth = 1000;
if (vDrawing.AbsWidth != 0)
{
vHeight = vWidth * (vDrawing.AbsHeight / vDrawing.AbsWidth);
if (vHeight > 4096)
{
vHeight = 4096;
}
vHeight = Math.Round(vHeight);
}
Bitmap vBitmap = new Bitmap((int)(vWidth), (int)(vHeight));
Note

We recommend using such kind of the Height and Width properties checks to avoid exceptions.

  1. Set DPI with the SetResolution method.
vBitmap.SetResolution(300, 300);
  1. Create an instance of the Graphics class.
Graphics vGr = Graphics.FromImage(vBitmap);
  1. Render the CAD file to vGr with the Draw method.
RectangleF vRect = new RectangleF(0, 0, (float)1000, (float)(vBitmap.Width * vDrawing.AbsHeight / vDrawing.AbsWidth));
vDrawing.Draw(vGr, vRect);
  1. Finally, export the CAD file to JPEG with the Save method.
vBitmap.Save(openFileDialog1.FileName + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);

You have created the function to export CAD files to JPEG with a specified DPI.

The full code listing.

...
using CADImport;


namespace WindowsFormsApp1
{
public partial class Form1 : Form

{
public Form1()
{
InitializeComponent();
}
private void ExportToJpeg_Click(object sender, EventArgs e)
{
if ((openFileDialog1.ShowDialog() != DialogResult.OK)) return;
CADImage vDrawing = CADImage.CreateImageByExtension(openFileDialog1.FileName);
vDrawing.LoadFromFile(openFileDialog1.FileName);
Double vHeight = 1;
Double vWidth = 1000;
if (vDrawing.AbsWidth != 0)
{
vHeight = vWidth * (vDrawing.AbsHeight / vDrawing.AbsWidth);
if (vHeight > 4096)
{
vHeight = 4096;
}
vHeight = Math.Round(vHeight);
}
Bitmap vBitmap = new Bitmap((int)(vWidth), (int)(vHeight));
vBitmap.SetResolution(300, 300);
Graphics vGr = Graphics.FromImage(vBitmap);
RectangleF vRect = new RectangleF(0, 0, (float)(vWidth), (float)(vHeight));
vDrawing.Draw(vGr, vRect);
vBitmap.Save(openFileDialog1.FileName + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}