using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
public class MainForm : Form
{
private PictureBox pictureBox1;
private void Form1_Load(object sender, EventArgs e)
{
ViewDWG viewDwg = new ViewDWG();
try
{
pictureBox1.Image = viewDwg.GetDwgImage("c:\\1.dwg");
}
catch (Exception ex)
{
MessageBox.Show($"错误: {ex.Message}");
}
}
}
public class ViewDWG
{
private struct BITMAPFILEHEADER
{
public short bfType;
public int bfSize;
public short bfReserved1;
public short bfReserved2;
public int bfOffBits;
}
public Image GetDwgImage(string fileName)
{
if (!File.Exists(fileName))
throw new FileNotFoundException("文件没有被找到");
using (FileStream dwgStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
using (BinaryReader br = new BinaryReader(dwgStream))
{
dwgStream.Seek(13, SeekOrigin.Begin);
int posSentinel = br.ReadInt32();
dwgStream.Seek(posSentinel + 30, SeekOrigin.Begin);
int typePreview = br.ReadByte();
if (typePreview != 2 && typePreview != 3)
throw new InvalidOperationException("不支持的缩略图格式");
int posBMP = br.ReadInt32();
int lenBMP = br.ReadInt32();
dwgStream.Seek(posBMP + 14, SeekOrigin.Begin);
short biBitCount = br.ReadInt16();
byte[] bmpInfo = br.ReadBytes(lenBMP);
BITMAPFILEHEADER biH = CreateBitmapFileHeader(biBitCount, lenBMP);
using (MemoryStream bmpStream = new MemoryStream())
using (BinaryWriter bmpr = new BinaryWriter(bmpStream))
{
WriteBitmapFileHeader(bmpr, biH);
bmpr.Write(bmpInfo);
bmpStream.Seek(0, SeekOrigin.Begin);
return Image.FromStream(bmpStream);
}
}
}
private BITMAPFILEHEADER CreateBitmapFileHeader(short biBitCount, int lenBMP)
{
BITMAPFILEHEADER biH;
biH.bfType = 19778; // 'BM'
biH.bfSize = 54 + (biBitCount < 9 ? 4 * (int)Math.Pow(2, biBitCount) : 0) + lenBMP;
biH.bfReserved1 = 0;
biH.bfReserved2 = 0;
biH.bfOffBits = 14 + 40 + 1024; // 图像数据偏移
return biH;
}
private void WriteBitmapFileHeader(BinaryWriter writer, BITMAPFILEHEADER biH)
{
writer.Write(biH.bfType);
writer.Write(biH.bfSize);
writer.Write(biH.bfReserved1);
writer.Write(biH.bfReserved2);
writer.Write(biH.bfOffBits);
}
}
标签:文件,biH,缩略图,C#,int,br,new,using,public From: https://www.cnblogs.com/guangzhiruijie/p/18517897