WIA设备批量扫描

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using WIA;
using System.IO;
using System.Drawing.Imaging;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Drawing.Drawing2D;

namespace printTest
{

    public partial class Form1 : Form
    {


        List<System.Drawing.Image> images = new List<System.Drawing.Image>();
        public static List<string> GetDevices()
        {
            List<string> devices = new List<string>();
            WIA.DeviceManager manager = new WIA.DeviceManager();
            foreach (WIA.DeviceInfo info in manager.DeviceInfos)
            {
                devices.Add(info.DeviceID);
            }
            return devices;
        }


        const string wiaFormatBMP = "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}";
        class WIA_DPS_DOCUMENT_HANDLING_SELECT
        {
            public const uint FEEDER = 0x00000001;
            public const uint FLATBED = 0x00000002;
        }
        class WIA_DPS_DOCUMENT_HANDLING_STATUS
        {
            public const uint FEED_READY = 0x00000001;
        }
        class WIA_PROPERTIES
        {
            public const uint WIA_RESERVED_FOR_NEW_PROPS = 1024;
            public const uint WIA_DIP_FIRST = 2;
            public const uint WIA_DPA_FIRST = WIA_DIP_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
            public const uint WIA_DPC_FIRST = WIA_DPA_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
            //
            // Scanner only device properties (DPS)
            //
            public const uint WIA_DPS_FIRST = WIA_DPC_FIRST + WIA_RESERVED_FOR_NEW_PROPS;
            public const uint WIA_DPS_DOCUMENT_HANDLING_STATUS = WIA_DPS_FIRST + 13;
            public const uint WIA_DPS_DOCUMENT_HANDLING_SELECT = WIA_DPS_FIRST + 14;
        }

        #region 画矩形使用到的变量
        Point p1;   //定义鼠标按下时的坐标点
        Point p2;   //定义移动鼠标时的坐标点
        Point p3;   //定义松开鼠标时的坐标点
        #endregion

        #region 缩放、裁剪图像用到的变量
        /// <summary>
        /// 
        /// </summary>
        int x1;     //鼠标按下时横坐标
        int y1;     //鼠标按下时纵坐标
        int width;  //所打开的图像的宽
        int heigth; //所打开的图像的高
        bool HeadImageBool = false;    // 此布尔变量用来判断pictureBox1控件是否有图片
        #endregion
        Bitmap Bi;  //定义位图对像
        public Form1()
        {
            InitializeComponent();
        }

        #region 扫描1
        private void btnScan_Click(object sender, EventArgs e)
        {

            listBox1.Items.Clear();
            lbDevices.Items.Clear();
            List<string> devices = GetDevices();

            foreach (string device in devices)
            {
                lbDevices.Items.Add(device);
            }
            //check if device is not available
            if (lbDevices.Items.Count == 0)
            {
                MessageBox.Show("没有任何可用的打印、扫描设备!");
                this.Close();
            }
            else
            {
                lbDevices.SelectedIndex = 0;
            }


            bool hasMorePages = true;
            string deviceID = (string)lbDevices.SelectedItem;
            while (hasMorePages)
            {
                //select the correct scanner using the provided scannerId parameter
                WIA.DeviceManager manager = new WIA.DeviceManager();
                WIA.Device device = null;
                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == deviceID)
                    {
                        // connect to scanner
                        device = info.Connect();
                        break;
                    }
                }
                // device was not found
                if (device == null)
                {
                    // enumerate available devices
                    string availableDevices = "";
                    foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                    {
                        availableDevices += info.DeviceID + "\n";
                    }

                    // show error with available devices
                    throw new Exception("The device with provided ID could not be found. Available Devices:\n" + availableDevices);
                }
                int i = device.Items.Count;
                WIA.Item item = device.Items[1] as WIA.Item;

                try
                {
                    // scan image
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                    WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);

                    // save to temp file
                    string fileName = Path.GetTempFileName();
                    File.Delete(fileName);
                    image.SaveFile(fileName);//保存temp文件
                    image = null;
                    int leng = @"C:\Users\ll\AppData\Local\Temp".Length;
                    // add file to output list
                    listBox1.Items.Add(fileName.Substring(leng, fileName.Length - leng));
                    //listBox1.Items.Add(fileName);
                    images.Add(System.Drawing.Image.FromFile(fileName));//C:\Users\ll\AppData\Local\Temp
                }
                catch (Exception exc)
                {
                    //MessageBox.Show(exc.Message);
                }
                finally
                {
                    item = null;
                    //determine if there are any more pages waiting
                    WIA.Property documentHandlingSelect = null;
                    WIA.Property documentHandlingStatus = null;
                    foreach (WIA.Property prop in device.Properties)
                    {
                        if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_SELECT)
                            documentHandlingSelect = prop;
                        if (prop.PropertyID == WIA_PROPERTIES.WIA_DPS_DOCUMENT_HANDLING_STATUS)
                            documentHandlingStatus = prop;
                    }

                    // assume there are no more pages
                    hasMorePages = false;

                    // may not exist on flatbed scanner but required for feeder
                    if (documentHandlingSelect != null)
                    {
                        // check for document feeder
                        if ((Convert.ToUInt32(documentHandlingSelect.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER) != 0)
                        {
                            hasMorePages = ((Convert.ToUInt32(documentHandlingStatus.get_Value()) & WIA_DPS_DOCUMENT_HANDLING_STATUS.FEED_READY) != 0);
                        }
                    }
                }
            }
            if (images.Count >= 0)
            {
                pictureBox1.Image = images[0];
                double imageX = pictureBox1.Image.Width;
                double imageY = pictureBox1.Image.Height;

                double picX = pictureBox1.Width;
                double pixY = pictureBox1.Height;

                //pictureBox2.Image = images[0];
                //pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            }
        } 
        #endregion

        #region 保存
        private void button1_Click(object sender, EventArgs e)
        {
            if (pictureBox2.Image != null)
            {
                string where = @"E:\" + DateTime.Now.ToString("yyyy-MM-dd HHmmss");
                //save scanned image into specific folder
                pictureBox2.Image.Save(where + ".jpeg", ImageFormat.Jpeg);

        //        //iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 716f);
        //        iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 716f);
        //        pageSize.BackgroundColor = new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xDE);
        //        iTextSharp.text.Image img1 = iTextSharp.text.Image.GetInstance(pictureBox1.Image, iTextSharp.text.BaseColor.WHITE);
        //        //设置边界
        //        //Document document = new Document(pageSize, 36f, 72f, 108f, 180f);
        //        Document document = new Document(pageSize, 36f, 72f, 108f, 180f);
        //        PdfWriter.GetInstance(document, new FileStream(where + ".pdf", FileMode.Create));
        //        // 添加文档信息
        //        document.AddTitle("PDFInfo");
        //        document.AddSubject("Demo of PDFInfo");
        //        document.AddKeywords("Info, PDF, Demo");
        //        document.AddCreator("SetPdfInfoDemo");
        //        document.AddAuthor("zeda");
        //        document.Open();
        //        // 添加文档内容
        //        document.Add(img1);
        //        document.Close();
            }
        } 
        #endregion

        #region 顺时针旋转
        private void button4_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image != null)
            {
                try
                {
                    Bitmap a = new Bitmap(pictureBox1.Image);//得到图片框中的图片
                    pictureBox1.Image = Rotate(a, 90);
                    //pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
                    pictureBox1.Location = panel1.Location;
                    pictureBox1.Refresh();//最后刷新图片框
                }
                catch { }
            }
        }
        #endregion

        #region 扫描4
        private void button5_Click(object sender, EventArgs e)
        {
            ImageFile imageFile = null;
            CommonDialogClass cdc = new WIA.CommonDialogClass();

            try
            {
                imageFile = cdc.ShowAcquireImage(WIA.WiaDeviceType.ScannerDeviceType,
                                                 WIA.WiaImageIntent.TextIntent,
                                                 WIA.WiaImageBias.MaximizeQuality,
                                                 "{00000000-0000-0000-0000-000000000000}",
                                                 true,
                                                 true,
                                                 false);

                string fileName = Path.GetTempFileName();
                File.Delete(fileName);
                if (imageFile != null)
                {
                    imageFile.SaveFile(fileName);//保存temp文件
                    imageFile = null;
                    int leng = @"C:\Users\ll\AppData\Local\Temp".Length;
                    // add file to output list
                    listBox1.Items.Add(fileName.Substring(leng, fileName.Length - leng));
                    //listBox1.Items.Add(fileName);
                    images.Add(System.Drawing.Image.FromFile(fileName));//C:\Users\ll\AppData\Local\Temp
                    foreach (System.Drawing.Image im in images)
                    {
                        string where = @"E:\" + DateTime.Now.ToString("yyyy-MM-dd HHmmss");
                        //save scanned image into specific folder
                        im.Save(where + ".jpeg", ImageFormat.Jpeg);
                    }
                }
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                imageFile = null;
            }
        }
        #endregion
        int i = 0;
        #region 增加
        private void button2_Click(object sender, EventArgs e)
        {
            i++;
            label1.Text = i.ToString();
            if (i < images.Count && i >= 0)
            {
                pictureBox1.Image = images[i];
                //pictureBox2.Image = images[i];
                //pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            }
        } 
        #endregion

        #region 减小
        private void button3_Click(object sender, EventArgs e)
        {
            i--;
            label1.Text = i.ToString();
            if (i < images.Count && i >= 0)
            {
                pictureBox1.Image = images[i];
                //pictureBox2.Image = images[i];
                //pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            }
        } 
        #endregion

        #region 旋转
        private void button6_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image != null)
            {
                try
                {
                    Bitmap a = new Bitmap(pictureBox1.Image);//得到图片框中的图片
                    pictureBox1.Image = Rotate(a, -90);
                    //pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
                    pictureBox1.Location = panel1.Location;
                    pictureBox1.Refresh();//最后刷新图片框
                }
                catch { }
            }
        } 
        #endregion


        #region 图片旋转函数
        /// <summary>
        /// 以逆时针为方向对图像进行旋转
        /// </summary>
        /// <param name="b">位图流</param>
        /// <param name="angle">旋转角度[0,360](前台给的)</param>
        /// <returns></returns>
        public Bitmap Rotate(Bitmap b, int angle)
        {
            angle = angle % 360;
 
            //弧度转换
            double radian = angle * Math.PI / 180.0;
            double cos = Math.Cos(radian);
            double sin = Math.Sin(radian);
 
            //原图的宽和高
            int w = b.Width;
            int h = b.Height;
            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
 
            //目标位图
            Bitmap dsImage = new Bitmap(W, H);
            Graphics g = Graphics.FromImage(dsImage);            
 
            g.InterpolationMode = InterpolationMode.Bilinear;
 
            g.SmoothingMode = SmoothingMode.HighQuality;
 
            //计算偏移量
            Point Offset = new Point((W - w) / 2, (H - h) / 2);
 
            //构造图像显示区域:让图像的中心与窗口的中心点一致
             System.Drawing.Rectangle rect = new  System.Drawing.Rectangle(Offset.X, Offset.Y, w, h);
            Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
            g.TranslateTransform(center.X, center.Y);
            g.RotateTransform(360 - angle);
 
            //恢复图像在水平和垂直方向的平移
            g.TranslateTransform(-center.X, -center.Y);
            g.DrawImage(b, rect);
 
            //重至绘图的所有变换
            g.ResetTransform();
 
            g.Save();
            g.Dispose();
            return dsImage;
        }
        #endregion 图片旋转函数更多 0

        private void Form1_Load(object sender, EventArgs e)
        {
            #region 滚动条
            panel2.AutoScroll = true;
            pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;

            panel3.AutoScroll = true;
            pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; 

            #endregion


            #region 自动缩放
            //pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            //pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;


            //pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
            //pictureBox2.Dock = System.Windows.Forms.DockStyle.Fill; 
            #endregion
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            this.Cursor = Cursors.Cross;
            this.p1 = new Point(e.X, e.Y);
            x1 = e.X;
            y1 = e.Y;
            if (this.pictureBox1.Image != null)
            {
                HeadImageBool = true;
            }
            else
            {
                HeadImageBool = false;
            }
        }

        #region 移动鼠标发生的事件
        /// <summary>
        /// 鼠标移动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (this.Cursor == Cursors.Cross)
            {
                this.p2 = new Point(e.X, e.Y);
                if ((p2.X - p1.X) > 0 && (p2.Y - p1.Y) > 0)     //当鼠标从左上角向开始移动时P3坐标
                {
                    this.p3 = new Point(p1.X, p1.Y);
                }
                if ((p2.X - p1.X) < 0 && (p2.Y - p1.Y) > 0)     //当鼠标从右上角向左下方向开始移动时P3坐标
                {
                    this.p3 = new Point(p2.X, p1.Y);
                }
                if ((p2.X - p1.X) > 0 && (p2.Y - p1.Y) < 0)     //当鼠标从左下角向上开始移动时P3坐标
                {
                    this.p3 = new Point(p1.X, p2.Y);
                }
                if ((p2.X - p1.X) < 0 && (p2.Y - p1.Y) < 0)     //当鼠标从右下角向左方向上开始移动时P3坐标
                {
                    this.p3 = new Point(p2.X, p2.Y);
                }
                this.pictureBox1.Invalidate();  //使控件的整个图面无效,并导致重绘控件
            }
        }
        #endregion


        #region 松开鼠标发生的事件,实例化ImageCut1类对像
        ImageCut1 IC1;  //定义所画矩形的图像对像
        /// <summary>
        /// 鼠标放开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (HeadImageBool)
            {
                width = this.pictureBox1.Image.Width;
                heigth = this.pictureBox1.Image.Height;
                if ((e.X - x1) > 0 && (e.Y - y1) > 0)   //当鼠标从左上角向右下方向开始移动时发生
                {
                    IC1 = new ImageCut1(x1, y1, Math.Abs(e.X - x1), Math.Abs(e.Y - y1));    //实例化ImageCut1类
                }
                if ((e.X - x1) < 0 && (e.Y - y1) > 0)   //当鼠标从右上角向左下方向开始移动时发生
                {
                    IC1 = new ImageCut1(e.X, y1, Math.Abs(e.X - x1), Math.Abs(e.Y - y1));   //实例化ImageCut1类
                }
                if ((e.X - x1) > 0 && (e.Y - y1) < 0)   //当鼠标从左下角向右上方向开始移动时发生
                {
                    IC1 = new ImageCut1(x1, e.Y, Math.Abs(e.X - x1), Math.Abs(e.Y - y1));   //实例化ImageCut1类
                }
                if ((e.X - x1) < 0 && (e.Y - y1) < 0)   //当鼠标从右下角向左上方向开始移动时发生
                {
                    IC1 = new ImageCut1(e.X, e.Y, Math.Abs(e.X - x1), Math.Abs(e.Y - y1));      //实例化ImageCut1类
                }

                if (IC1 != null)
                {
                    this.pictureBox2.Width = (IC1.KiCut1((Bitmap)(this.pictureBox1.Image))).Width;
                    this.pictureBox2.Height = (IC1.KiCut1((Bitmap)(this.pictureBox1.Image))).Height;
                    this.pictureBox2.Image = IC1.KiCut1((Bitmap)(this.pictureBox1.Image));

                    //this.pictureBox2.Image = IC1.KiCut1((Bitmap)(this.pictureBox1.Image));
                    //boolShow1 = true;
                    //else if (pictureBox3.Image == null)
                    //{
                    //    this.pictureBox3.Image = IC1.KiCut1((Bitmap)(this.pictureBox1.Image));
                    //    boolShow2 = true;
                    //}
                    //else
                    //{
                    //    if (boolShow2 == true)
                    //    {
                    //        this.pictureBox2.Image = IC1.KiCut1((Bitmap)(this.pictureBox1.Image));
                    //        boolShow1 = true;
                    //        boolShow2 = false;
                    //    }
                    //    else
                    //    {
                    //        this.pictureBox3.Image = IC1.KiCut1((Bitmap)(this.pictureBox1.Image));
                    //        boolShow1 = false;
                    //        boolShow2 = true;
                    //    }
                    //}
                }
                this.Cursor = Cursors.Default;
            }
            else
            {
                this.Cursor = Cursors.Default;
            }
        }
        #endregion


        #region 重新绘制pictureBox1控件,即移动鼠标画矩形
        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (HeadImageBool)
            {
                Pen p = new Pen(Color.Black, 1);//画笔
                p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                //Bitmap bitmap = new Bitmap(strHeadImagePath);
                Bitmap bitmap = Bi;
                System.Drawing.Rectangle rect = new System.Drawing.Rectangle(p3, new Size(System.Math.Abs(p2.X - p1.X), System.Math.Abs(p2.Y - p1.Y)));
                e.Graphics.DrawRectangle(p, rect);

            }
            else
            {
            }
        }
        #endregion

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //string fileName = DateTime.Now.ToString("yyyyMMddhhmmss");
            //string path = Path.GetFullPath("images/");
            //string[] files = Directory.GetFiles(path);
            //foreach (string file in files)
            //{
            //    if (file == path + fileName + ".jpg")
            //    {
            //        return;
            //    }

            //}
            //using (Stream stream = new FileStream(path + fileName + ".jpg", FileMode.Create))
            //{
            //    using (FileStream fs = new FileStream(listBox1.SelectedItem.ToString(), FileMode.Open))
            //    {
            //        byte[] bytes = new byte[1024 * 10];
            //        int len;
            //        while ((len = fs.Read(bytes, 0, bytes.Length)) > 0)
            //        {
            //            stream.Write(bytes, 0, len);

            //        }
            //    }
            //}
            //System.Drawing.Image image = System.Drawing.Image.FromFile(path + fileName + ".jpg");
            //pictureBox1.Image = image;
        }

       
    }
}

posted @ 2015-07-29 16:27  HongMaJu  阅读(1308)  评论(0编辑  收藏  举报