/// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images.</returns>
        public override List<Image> Scan()
        {
            Console.WriteLine("Scan WIA");
            List<Image> images = new List<Image>();
            bool hasMorePages = true;
            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);
                }
                WIA.Item item = device.Items[1] as WIA.Item;
                try
                {
                    foreach (Property prop in item.Properties)
                    {
                        switch (prop.PropertyID)
                        {
                            case 6146: //1 : couleur, 2 : gris, 4 : binaire
                                SetProperty(prop, 2);
                                break;
                            case 6147: //ppp horizontal
                                SetProperty(prop, MainWindow.numerisationDPI);
                                break;
                            case 6148: //ppp vertical
                                SetProperty(prop, MainWindow.numerisationDPI);
                                break;
                            case 6149: //x point where to start scan
                                SetProperty(prop, 0);
                                break;
                            case 6150: //y-point where to start scan
                                SetProperty(prop, 0);
                                break;
                        }
                    }

                    // scan image
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                    WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, EnvFormatID.wiaFormatTIFF, false);

                    if(image == null)
                    {
                        Console.WriteLine("Numérisation annulé");
                        return null;
                    }

                    // save to temp file
                    string fileName = Path.GetTempFileName();
                    File.Delete(fileName);
                    image.SaveFile(fileName);
                    image = null;
                    // add file to output list
                    images.Add(Image.FromFile(fileName));
                }
                catch (System.ArgumentException e)
                {
                    Console.WriteLine("Le PPP spécifié n'est pas supporté par le scanner");
                    throw e;
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                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);
                        }
                    }
                }
            }
            return images;
        }
示例#2
0
 private void button1_Click(object sender, EventArgs e)
 {
     withFeeder = false;
     WIA.ImageFile Img = null;
     Scanner = null;
     try
     {
         if (Scanner == null)
         {
             if (chooseDevice())
             {
                 InitializeITEM();                                   //inicjuje ustawienia skanera
                 Img        = (ImageFile)Dialog1.ShowTransfer(Scanner.Items[1], wiaFormatBMP, true);
                 imageBytes = (byte[])Img.FileData.get_BinaryData(); // <– Converts the ImageFile to a byte array
                 MemoryStream ms    = new MemoryStream(imageBytes);
                 Image        image = Image.FromStream(ms);
                 pictureBox1.Image = image;
             }
             else
             {
                 InitializeITEM();                                   //inicjuje ustawienia skanera
                 Img        = (ImageFile)Dialog1.ShowTransfer(Scanner.Items[1], wiaFormatBMP, true);
                 imageBytes = (byte[])Img.FileData.get_BinaryData(); // <– Converts the ImageFile to a byte array
                 MemoryStream ms    = new MemoryStream(imageBytes);
                 Image        image = Image.FromStream(ms);
                 pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
                 pictureBox1.Image    = image;
                 return;
             }
         }
         else
         {
             InitializeITEM();//inicjuje ustawienia skanera
             Img = (ImageFile)Dialog1.ShowTransfer(Scanner.Items[1], wiaFormatBMP, true);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Skanuj...",
                         MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     finally
     {
         if (Img != null)
         {
             Marshal.ReleaseComObject(Img);
         }
     }
 }
示例#3
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                commonDialog = new CommonDialog();
                countScannings++;

                chooseScanner();

                Device connectedDevice = scanner.Connect();
                Item   scannerItem     = connectedDevice.Items[1];

                AdjustScannerSettings(scannerItem, resolution, 0, 0, scanWidth, scanHeight, scanBrightness, scanContrast, scanColorMode);
                SetDeviceIntProperty(ref connectedDevice, 3088, 1);
                SetDeviceIntProperty(ref connectedDevice, 3096, 1);

                ImageFile image = commonDialog.ShowTransfer(scannerItem, formatID, true);

                filePath += @"\";
                filePath += countScannings.ToString();
                filePath += "scan";

                if (radioButtonBMP.Checked)
                {
                    filePath += ".bmp";
                }
                if (radioButtonPNG.Checked)
                {
                    filePath += ".png";
                }
                if (radioButtonJPEG.Checked)
                {
                    filePath += ".jpeg";
                }
                if (radioButtonTIFF.Checked)
                {
                    filePath += ".tiff";
                }

                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                image.SaveFile(filePath);

                MessageBox.Show(success);

                Image image2 = Image.FromFile(filePath);
                pictureBox1.Image = ResizeImage(image2, pictureBox1.Width, pictureBox1.Height);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
示例#4
0
        private void button1_Click(object sender, EventArgs e)
        {
            Item   item  = scanner.Items[1];
            object image = wia_dialog.ShowTransfer(item, "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}", false);

            scan = (ImageFile)image;

            var file_bytes = (byte[])scan.FileData.get_BinaryData();
            var stream     = new MemoryStream(file_bytes);

            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox1.Image    = Image.FromStream(stream);
        }
示例#5
0
        /// <summary>
        /// Scan a image with JPEG Format
        /// </summary>
        /// <returns></returns>
        public ImageFile ScanJPEG()
        {
            // Connect to the device and instruct it to scan
            // Connect to the device
            var device = this._deviceInfo.Connect();

            // Select the scanner
            WIA.CommonDialog dlg = new WIA.CommonDialog();

            var item = device.Items[1];

            try
            {
                AdjustScannerSettings(item, resolution, 0, 0, width_pixel, height_pixel, 0, 0, color_mode);

                object scanResult = dlg.ShowTransfer(item, EnvFormatID.wiaFormatJPEG, true);

                if (scanResult != null)
                {
                    var imageFile = (ImageFile)scanResult;

                    // Return the imageFile
                    return(imageFile);
                }
            }
            catch (COMException e)
            {
                // Display the exception in the console.
                Console.WriteLine(e.ToString());

                uint errorCode = (uint)e.ErrorCode;

                // Catch 2 of the most common exceptions
                if (errorCode == 0x80210006)
                {
                    MessageBox.Show("The scanner is busy or isn't ready");
                }
                else if (errorCode == 0x80210064)
                {
                    MessageBox.Show("The scanning process has been cancelled.");
                }
                else
                {
                    MessageBox.Show("A non catched error occurred, check the console. Error code: " + errorCode, "Error", MessageBoxButtons.OK);
                }
            }

            return(new ImageFile());
        }
示例#6
0
        public List <Image> start()
        {
            List <Image> imageLost = new List <Image>();

            WIA.CommonDialog dialog = new WIA.CommonDialog();
            WIA.Device       device = dialog.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType);
            WIA.Items        items  = dialog.ShowSelectItems(device);
            WIA.ImageFile    image  = null;
            dialog = new WIA.CommonDialog();
            foreach (WIA.Item item in items)
            {
                while (true)
                {
                    Console.WriteLine(device.Commands);

                    try
                    {
                        if (stop == true)
                        {
                            image = null;
                            stop  = false;
                        }
                        else
                        {
                            image = (WIA.ImageFile)dialog.ShowTransfer(item, "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}", false);
                        }
                        if ((image != null) && (image.FileData != null))
                        {
                            WIA.Vector vector = image.FileData;
                            imageLost.Add(Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData())));
                        }
                    }
                    catch (System.Runtime.InteropServices.COMException)
                    {
                        return(imageLost);
                    }
                    finally
                    {
                        if (image != null)
                        {
                            Marshal.FinalReleaseComObject(image);
                        }
                    }
                }
            }
            return(imageLost);
        }
示例#7
0
        ImageFile Scan(String str)
        {
            LogContent("process", "Scanning");
            CommonDialog dialog       = new WIA.CommonDialog();
            ImageFile    scannedImage = null;

            if (Set.default_device == null)
            {
                WiaDev = dialog.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
                MessageBoxResult result = MessageBox.Show("Ustawić urządzenie jako domyślne?", "Potwierdzenie", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    Set.default_device = WiaDev;
                }
            }
            else
            {
                WiaDev = Set.default_device;
            }

            //Start Scan

            WIA.Item Item = WiaDev.Items[1] as WIA.Item;

            try
            {
                scannedImage = (ImageFile)dialog.ShowTransfer(Item, EnvFormatID.wiaFormatPNG, false);
                String path = Set.path;
                destination = path + str + "_" + Note.Text + ".png";
                LogContent("destination", destination);
                scannedImage.SaveFile(destination);
                return(scannedImage);
            }
            catch (Exception e)
            {
                MessageBox.Show("Error " + e.Message);
            }
            finally
            {
            }
            return(null);
        }
        private void Scan_Click(object sender, RoutedEventArgs e)
        {
            ICommonDialog dialog = new WIA.CommonDialog();
            DeviceInfo    device = null;

            for (int i = 1; i <= manager.DeviceInfos.Count; i++)
            {
                if (manager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType)
                {
                    continue;
                }

                device = manager.DeviceInfos[i];

                break;
            }

            if (device == null)
            {
                MessageBox.Show("Scanner doesn't attached", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var  d    = device.Connect();
            Item item = d.Items[1];

            SetWIAProperty(item.Properties, WIA_HORIZONTAL_SCAN_RESOLUTION_DPI, 300);
            SetWIAProperty(item.Properties, WIA_VERTICAL_SCAN_RESOLUTION_DPI, 300);
            ImageFile image = (ImageFile)dialog.ShowTransfer(item, FormatID.wiaFormatJPEG, true);

            if (image == null)
            {
                return;
            }
            imageBytes    = (byte[])image.FileData.get_BinaryData();
            OriginalImage = (Bitmap)Image.FromStream(new MemoryStream(imageBytes));
            OriginalImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
            CroppedImage = OriginalImage.Clone() as Bitmap;
            ImageScale   = (float)Width / OriginalImage.Width;
            MakeScaledImage();
        }
示例#9
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images path.</returns>
        public static List <string> Scan(string scannerId, DoWorkEventArgs e)
        {
            List <string> images       = new List <string>();
            bool          hasMorePages = true;
            ITempFilesResource <ImageFile> tempFiles = TempFilesScannerResource <ImageFile> .DefaultInstance();

            while (hasMorePages && !e.Cancel)
            {
                // 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 == scannerId)
                    {
                        // 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);
                }
                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 = tempFiles.SaveFile(image);
                    image = null;
                    // add file to output list
                    images.Add(fileName);
                }
                catch (System.Runtime.InteropServices.COMException exc)
                {
                    Debug.WriteLine(exc.Message);
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(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 (!e.Cancel)
            {
                return(images);
            }
            else
            {
                foreach (var image in images)
                {
                    tempFiles.DeleteFile(image);
                }
                images.Clear();
                return(images);
            }
        }
示例#10
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images.</returns>
        public static List <string> Scan(ScanSettings settings)
        {
            List <string> images       = new List <string>();
            bool          hasMorePages = true;

            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 == settings.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);
                }
                WIA.Item item = device.Items[1] as WIA.Item;
                try
                {
                    // scan image
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                    WIAScanner.AdjustScannerSettings(item, settings.WIA_Intent);
                    WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);

                    var imageBytes = (byte[])image.FileData.get_BinaryData();
                    images.Add(Convert.ToBase64String(imageBytes));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                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);
                        }
                    }
                }
            }
            return(images);
        }
示例#11
0
        public static List <Bitmap> Scan(string scannername)
        {
            List <Bitmap> images = new List <Bitmap>();

            bool hasMorePages = true;

            while (hasMorePages)
            {
                WIA.DeviceManager manager = new WIA.DeviceManager();
                WIA.Device        device  = null;
                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.Properties["Name"].get_Value().ToString() == scannername)
                    {
                        device = info.Connect();
                        break;
                    }
                }

                if (device == null)
                {
                    string availableDevices = "";
                    foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                    {
                        availableDevices += info.Properties["Name"].get_Value().ToString() + "\n";
                    }


                    throw new Exception("Указанное устройство не найдено. Доступные устройства: " + availableDevices);
                }

                WIA.Item item = device.Items[1] as WIA.Item;
                try
                {
                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                    AdjustScannerSettings(item, 100, 0, 0, 850, 1170, 0, 0, true);
                    WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, wiaFormatBMP, false);

                    //темповый файл
                    string fileName = Path.GetTempFileName();
                    File.Delete(fileName);
                    image.SaveFile(fileName);
                    image = null;
                    images.Add(new Bitmap(fileName));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                finally
                {
                    item = null;


                    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;
                        }
                    }


                    hasMorePages = false;


                    if (documentHandlingSelect != null)
                    {
                        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);
                        }
                    }
                }
            }

            return(images);
        }
        private void btn_scannen_Click(object sender, EventArgs e)
        {
            if (rdb_spl.Checked)
            {
                btn_scannen.Enabled      = false;
                tbx_name.Enabled         = false;
                tbx_bemerkung.Enabled    = false;
                dtp_datum.Enabled        = false;
                lbx_dokument_typ.Enabled = false;
                string           wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
                WIA.CommonDialog cd            = new WIA.CommonDialog();
                WIA.Device       dev           = null;
                dev = cd.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
                dev.Properties["Pages"].set_Value(1);
                //dev.Properties["3088"].set_Value(5);
                Item dt = dev.Items[1];
                dt.Properties["6147"].set_Value(300);
                dt.Properties["6148"].set_Value(300);
                try
                {
                    int counter = -1;
                    while (true)
                    {
                        counter++;
                        WIA.CommonDialog common = new WIA.CommonDialog();
                        ImageFile        image  = common.ShowTransfer(dev.Items[1], wiaFormatJPEG, true);
                        pfad = Hauptfenster.tempo_pfad + @"\" + tbx_name.Text + counter.ToString() + ".jpg";
                        Byte[]               imageBytes = (byte[])image.FileData.get_BinaryData();
                        MemoryStream         ms         = new MemoryStream(imageBytes);
                        System.Drawing.Image img        = System.Drawing.Image.FromStream(ms);
                        JpegBildKomprimieren(img, int.Parse(textBox1.Text), pfad);
                        //image.SaveFile(pfad);
                    }
                }
                catch (Exception)
                {
                }
                btn_erstellen.Enabled = true;
            }
            else if (rdb_dpl.Checked)
            {
                btn_scannen.Enabled      = false;
                tbx_name.Enabled         = false;
                tbx_bemerkung.Enabled    = false;
                dtp_datum.Enabled        = false;
                lbx_dokument_typ.Enabled = false;
                string           wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
                WIA.CommonDialog cd            = new WIA.CommonDialog();
                WIA.Device       dev           = null;
                dev = cd.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
                dev.Properties["Pages"].set_Value(1);
                //dev.Properties["3088"].set_Value(5);
                Item dt = dev.Items[1];
                dt.Properties["6147"].set_Value(300);
                dt.Properties["6148"].set_Value(300);
                int counter = -1;
                try
                {
                    while (true)
                    {
                        counter += 2;
                        WIA.CommonDialog common = new WIA.CommonDialog();
                        ImageFile        image  = common.ShowTransfer(dev.Items[1], wiaFormatJPEG, true);
                        if (counter < 10)
                        {
                            pfad = Hauptfenster.tempo_pfad + @"\0" + counter.ToString() + ".jpg";
                        }
                        else
                        {
                            pfad = Hauptfenster.tempo_pfad + @"\" + counter.ToString() + ".jpg";
                        }
                        Byte[]               imageBytes = (byte[])image.FileData.get_BinaryData();
                        MemoryStream         ms         = new MemoryStream(imageBytes);
                        System.Drawing.Image img        = System.Drawing.Image.FromStream(ms);
                        JpegBildKomprimieren(img, int.Parse(textBox1.Text), pfad);
                        //image.SaveFile(pfad); !
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Scannen abgeschlossen");
                }
                #region Alt_Dup
                if (MessageBox.Show("Rückseite eingelegt?", "Duplex", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    dt.Properties["6147"].set_Value(300);
                    dt.Properties["6148"].set_Value(300);
                    try
                    {
                        int counter2 = counter + 1;
                        while (true)
                        {
                            counter2 -= 2;
                            WIA.CommonDialog common = new WIA.CommonDialog();
                            ImageFile        image  = common.ShowTransfer(dev.Items[1], wiaFormatJPEG, true);
                            if (counter2 < 10)
                            {
                                pfad = Hauptfenster.tempo_pfad + @"\0" + counter2.ToString() + ".jpg";
                            }
                            else
                            {
                                pfad = Hauptfenster.tempo_pfad + @"\" + counter2.ToString() + ".jpg";
                            }
                            Byte[]               imageBytes = (byte[])image.FileData.get_BinaryData();
                            MemoryStream         ms         = new MemoryStream(imageBytes);
                            System.Drawing.Image img        = System.Drawing.Image.FromStream(ms);
                            JpegBildKomprimieren(img, int.Parse(textBox1.Text), pfad);
                            //image.SaveFile(pfad);
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Scannen abgeschlossen");
                    }
                }
                else
                {
                    string[] a = System.IO.Directory.GetFiles(Hauptfenster.tempo_pfad);
                    for (int i = 0; i < a.Length; i++)
                    {
                        try
                        {
                            System.IO.File.Delete(a[i]);
                        }
                        catch (Exception)
                        {
                        }
                    }
                    this.Close();
                }

                #endregion
                btn_erstellen.Enabled = true;
            }
            #region lustiger toter Code
            //try
            //{
            //WIA.CommonDialog wcd = new WIA.CommonDialog();
            //Device d = wcd.ShowSelectDevice(WiaDeviceType.ScannerDeviceType, true, false);
            //int c = 0;
            //pfad = Hauptfenster.tempo_pfad + @"\" + tbx_name.Text + c.ToString() + ".jpg";
            //while (true)
            //{
            //    WIA.ImageFile img = new ImageFile();
            //    WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog();
            //    WIA.Item Item = d.Items[1] as WIA.Item;
            //    img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, wiaFormatJPEG, false);
            //    c++;
            //    pfad = Hauptfenster.tempo_pfad + @"\" + tbx_name.Text + c.ToString() + ".jpg";
            //    MessageBox.Show(pfad);
            //    img.SaveFile(pfad);

            //}
            //btn_erstellen.Enabled = true;
            //}
            //catch (Exception)
            //{
            //    MessageBox.Show("Es konnte keine Verbindung zum Scanner hergestellt werden!");
            //    btn_erstellen.Enabled = true;
            //}
            //try
            //{
            //    int c = 0;
            //    const string wiaFormatJPEG = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
            //    WIA.CommonDialog wiaDiag = new WIA.CommonDialog();
            //    WIA.ImageFile wiaImage = null;
            //    while (true)
            //    {
            //        wiaImage = wiaDiag.ShowAcquireImage(
            //        WiaDeviceType.ScannerDeviceType,
            //        WiaImageIntent.GrayscaleIntent,
            //        WiaImageBias.MaximizeQuality,
            //        wiaFormatJPEG, true, true, false);

            //        WIA.Vector vector = wiaImage.FileData;
            //        Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData()));
            //        c++;
            //        pfad = Hauptfenster.tempo_pfad + @"\" + tbx_name.Text + c.ToString() + ".jpg";
            //        i.Save(pfad);
            //    }
            //}
            //catch (Exception)
            //{

            //  btn_erstellen.Enabled = true;
            //}
            #endregion
        }
示例#13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="scannerId"></param>
        /// <param name="qualidade"></param>
        /// <param name="tamanho"></param>
        /// <param name="tipo"></param>
        /// <returns></returns>
        private static List <KeyValuePair <string, Image> > DigitalizaItensEspecifico(string scannerId, WIAScanQuality qualidade, WIAPageSize tamanho, TipoLeituraDocumento tipo)
        {
            List <KeyValuePair <string, Image> > images = new List <KeyValuePair <string, Image> >();
            //Dictionary<string,Image> images = new Dictionary<string,Image>();
            bool hasMorePages = true;

            WIA.Item item;


            Mensagens = new HashSet <string>();

            // 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 == scannerId)
                {
                    device = info.Connect();
                    //AcquireNormal(device);
                    Dispositivos[scannerId].Propriedades.Clear();
                    CarregaPropriedades(device, Dispositivos[scannerId].Propriedades);
                    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
                Mensagens.Add("Não foi possível conectar-se ao o dispositivo especificado\n" + availableDevices);
            }

            ConfiguraTipoScan(ref device, tipo);

            item = device.Items[1] as WIA.Item;

            AjustaPropriedadesDispositivo(item, 0, 0, 0, 0, 1, qualidade, tamanho);
            WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
            while (hasMorePages)
            {
                try
                {
                    //Some scanner need WIA_DPS_PAGES to be set to 1, otherwise all pages are acquired but only one is returned as ImageFile
                    GravaPropriedade(ref device, DEVICE_PROPERTY_PAGES_ID, 1);

                    //Scan image
                    WIA.ImageFile image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, WIA.FormatID.wiaFormatPNG, false);
                    if (image != null)
                    {
                        // save to  file
                        string fileName = SalvarPNG(image);
                        images.Add(new KeyValuePair <string, Image>(fileName, Image.FromFile(fileName)));
                    }

                    //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);
                        }
                    }
                }
                catch (Exception exc)
                {
                    int error = CodigoErroWIA(exc);
                    Mensagens.Add(DescricaoErro(exc));
                    if (error == WIA_ERROR_PAPER_EMPTY)
                    {
                        hasMorePages = false;
                    }
                    if (error == 0)
                    {
                        throw exc;
                    }
                }
            }



            device = null;
            return(images);
        }
示例#14
0
        /// <summary>
        /// Scan Page,
        /// </summary>
        /// <param name="wia">Connected Device</param>
        /// <param name="pageSize">Page Size. A4, A3, A2 Etc</param>
        /// <param name="RotatePage">Rotation of page while scanning</param>
        public void Scan(bool rotatePage, int DPI, string filepath, bool useAdf, bool duplex)  //PageSize pageSize,
        {
            int  pages        = 0;
            bool hasMorePages = false;

            string[] sourceFiles = new string[100];

            WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog();

            try
            {
                do
                {
                    //  Connect to Device
                    Device   wia  = Connect();
                    WIA.Item item = wia.Items[1] as WIA.Item;

                    //  Setup ADF
                    if ((useAdf) || (duplex))
                    {
                        SetupADF(wia, duplex);
                    }

                    //  Setup Page Size
                    //  SetupPageSize(wia, rotatePage, A4, DPI, item);

                    WIA.ImageFile imgFile        = null;
                    WIA.ImageFile imgFile_duplex = null; //  if duplex is setup, this will be back page

                    imgFile = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);

                    //  If duplex page, get back page now.
                    if (duplex)
                    {
                        imgFile_duplex = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);
                    }

                    string varImageFileName = filepath + "\\Scanned" + ".jpeg";

                    Delete_File(varImageFileName); //  if file already exists. delete it.
                    imgFile.SaveFile(varImageFileName);

                    using (var src = new System.Drawing.Bitmap(varImageFileName))
                        using (var bmp = new System.Drawing.Bitmap(1000, 1000, System.Drawing.Imaging.PixelFormat.Format32bppPArgb))
                            using (var gr = System.Drawing.Graphics.FromImage(bmp))
                            {
                                gr.Clear(System.Drawing.Color.Blue);
                                gr.DrawImage(src, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height));
                                gr.DrawString("This is vivek", new System.Drawing.Font("Arial", 15, System.Drawing.FontStyle.Regular), System.Drawing.SystemBrushes.WindowText, new System.Drawing.Point(550, 20));
                                bmp.Save(System.Configuration.ConfigurationSettings.AppSettings["Path"] + "test" + pages + ".jpeg", System.Drawing.Imaging.ImageFormat.Png);

                                ////string imgPath = "test" + pages + ".tiff";
                                ////sourceFiles[pages] = imgPath;
                                //mergeTiffPages(string str_DestinationPath, string[] sourceFiles)
                            }
                    MergeTiffPages(@"D:\Test\", sourceFiles);

                    string varImageFileName_duplex;

                    if (duplex)
                    {
                        varImageFileName_duplex = filepath + "\\Scanned-" + pages.ToString() + ".tiff";
                        Delete_File(varImageFileName_duplex); //if file already exists. delete it.
                        imgFile_duplex.SaveFile(varImageFileName);
                    }

                    //Check with scanner to see if there are more pages.
                    if (useAdf || duplex)
                    {
                        hasMorePages = HasMorePages(wia);
                        pages++;
                    }
                }while (hasMorePages);
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                //throw new System.Exception(CheckError((uint)ex.ErrorCode));
            }
        }
示例#15
0
        private void scanButton_Click(object sender, RoutedEventArgs e)
        {
            //filePath = namefile();
            filePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(),"RESUME_SCANNER_image.tif");
            System.IO.File.Delete(filePath);

            dialog = new WIA.CommonDialog();

            try
            {
                scanner = dialog.ShowSelectDevice(
              WiaDeviceType.ScannerDeviceType, false, false);
            }
            catch (Exception msg)
            {
                //Uri uri = new Uri("Images/scanned.tif", UriKind.Relative);
                Uri uri = new Uri("Images/nnenna_u_resume.tif", UriKind.Relative);
                var stream = Application.GetResourceStream(uri).Stream;
                using (FileStream fileStream = System.IO.File.Create(filePath, (int)stream.Length))
                {
                    // Fill the bytes[] array with the stream data
                    byte[] bytesInStream = new byte[stream.Length];
                    stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

                    // Use FileStream object to write to the specified file
                    fileStream.Write(bytesInStream, 0, bytesInStream.Length);
                }
            }

            if (scanner!=null)
            {
                foreach (Property item in scanner.Items[1].Properties)
                {
                    switch (item.PropertyID)
                    {
                        case 6146: //4 is Black-white,gray is 2, color 1
                            SetProperty(item, 4);
                            break;
                        case 6147: //dots per inch/horizontal
                            SetProperty(item, 300);
                            break;
                        case 6148: //dots per inch/vertical
                            SetProperty(item, 300);
                            break;
                        case 6149: //x point where to start scan
                            SetProperty(item, 0);
                            break;
                        case 6150: //y-point where to start scan
                            SetProperty(item, 0);
                            break;
                        case 3096: //Pages
                            SetProperty(item, 1);
                            break;
                        case 3097: //PageSize
                            SetProperty(item, 1);
                            break;
                        case 6151: //horizontal exent
                            SetProperty(item, (int)(8.5 * 300));
                            break;
                        case 6152: //vertical extent
                            SetProperty(item, (int)(11 * 300));
                            break;
                        case 4103: //DataType
                            SetProperty(item, 0);
                            break;
                        case 4104: //BitsPerPixel
                            SetProperty(item, 1);
                            break;
                        case 4110: //BitsPerChannel
                            SetProperty(item, 1);
                            break;
                        case 4114: //NumberOfLines
                            SetProperty(item, 3300);
                            break;
                        case 4116: //ItemSize
                            SetProperty(item, 1056062);
                            break;
                        case 4113: //Bytes Per Line
                            SetProperty(item, 320);
                            break;
                    }
                }

                dialog.ShowSelectItems(scanner);

                ImageFile image = null;
                try
                {
                    image = dialog.ShowTransfer(scanner.Items[1], FormatID.wiaFormatTIFF, false) as ImageFile;
                }
                catch (Exception msg)
                {

                    if (msg.Message.Contains("HRESULT"))
                        MessageBox.Show("Please insert paper into scanner and try again.");
                    return;

                }
                //System.IO.File.Delete(filePath);

                image.SaveFile(filePath);
            }

            BitmapImage _image = new BitmapImage();
            _image.BeginInit();
            _image.CacheOption = BitmapCacheOption.None;
            _image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
            _image.CacheOption = BitmapCacheOption.OnLoad;
            _image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
            _image.UriSource = new Uri(filePath, UriKind.RelativeOrAbsolute);
            _image.EndInit();
            scannedImageHolder.Source = _image;
        }
示例#16
0
        void Scan(string directory, ScanColor clr, int dpi)
        {
            string deviceid;

            //Choose Scanner
            WIA.CommonDialog class1 = new WIA.CommonDialog();
            Device           d      = class1.ShowSelectDevice(WiaDeviceType.UnspecifiedDeviceType, true, false);

            if (d != null)
            {
                deviceid = d.DeviceID;
            }
            else
            {
                //no scanner chosen
                return;
            }
            WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog();
            bool             hasMorePages    = true;
            int x        = 0;
            int numPages = 0;

            while (hasMorePages)
            {
                //Create DeviceManager
                DeviceManager manager = new DeviceManager();
                Device        WiaDev  = null;
                foreach (DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == deviceid)
                    {
                        WIA.Properties infoprop = null;
                        infoprop = info.Properties;
                        //connect to scanner
                        WiaDev = info.Connect();
                        break;
                    }
                }
                //Start Scan
                WIA.ImageFile img  = null;
                WIA.Item      Item = WiaDev.Items[1] as WIA.Item;
                //set properties //BIG SNAG!! if you call WiaDev.Items[1] apprently it erases the item from memory so you cant call it again
                Item.Properties["6146"].set_Value((int)clr);//Item MUST be stored in a variable THEN the properties must be set.
                Item.Properties["6147"].set_Value(dpi);
                Item.Properties["6148"].set_Value(dpi);
                const string wiaFormatJPEG    = "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}";
                string       varImageFileName = "";
                try
                {//WATCH OUT THE FORMAT HERE DOES NOT MAKE A DIFFERENCE... .net will load it as a BITMAP!
                    img = (ImageFile)WiaCommonDialog.ShowTransfer(Item, wiaFormatJPEG, false);
                    //process image:
                    //Save to file and open as .net IMAGE
                    //string varImageFileName = Path.GetTempFileName();
                    varImageFileName = directory + numPages.ToString() + ".jpg";
                    if (File.Exists(varImageFileName))
                    {
                        //file exists, delete it
                        File.Delete(varImageFileName);
                    }
                    img.SaveFile(varImageFileName);
                    Image ret = Image.FromFile(varImageFileName);
                    EventHandler <WiaImageEventArgs> temp = Scanning;
                    if (temp != null)
                    {
                        temp(this, new WiaImageEventArgs(ret));
                    }
                    numPages++;
                    img = null;
                }
                catch (Exception)
                {
                    MessageBox.Show("Beim Scannen ist ein Fehler aufgetreten!");
                }
                finally
                {
                    Item = null;
                    //determine if there are any more pages waiting
                    Property documentHandlingSelect = null;
                    Property documentHandlingStatus = null;

                    foreach (Property prop in WiaDev.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;
                        }
                    }
                    hasMorePages = false; //assume there are no more pages
                    WIA_DPS_DOCUMENT_HANDLING_SELECT.FEEDER.ToString();
                    if (documentHandlingSelect != null)
                    //may not exist on flatbed scanner but required for feeder
                    {
                        //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);
                        }
                    }
                    x++;
                }
                WiaDev = null;
            }
            EventHandler tempCom = ScanComplete;

            if (tempCom != null)
            {
                tempCom(this, EventArgs.Empty);
            }
        }
示例#17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="scannerId"></param>
        /// <param name="qualidade"></param>
        /// <param name="tamanho"></param>
        /// <param name="tipo"></param>
        /// <returns></returns>
        private static List <KeyValuePair <string, Image> > DigitalizaItens(string scannerId, WIAScanQuality qualidade, WIAPageSize tamanho, TipoLeituraDocumento tipo)
        {
            List <KeyValuePair <string, Image> > images = new List <KeyValuePair <string, Image> >();
            //Dictionary<string,Image> images = new Dictionary<string,Image>();
            bool hasMorePages = true;

            WIA.Item item;

            Mensagens = new HashSet <string>();
            while (hasMorePages)
            {
                // select the correct scanner using the provided scannerId parameter
                WIA.Device device = LocalizaDispositio(scannerId);

                try
                {
                    //SetWIAProperty(device.Properties, WIA_DEVICE_PROPERTY_PAGES_ID, 1);
                    //Escolha da forma de scaneamento, Feeder ou Flatbad
                    ConfiguraTipoScan(ref device, tipo);

                    item = device.Items[1] as WIA.Item;

                    AjustaPropriedadesDispositivo(item, 0, 0, 0, 0, 1, qualidade, tamanho);
                    // scan image

                    WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
                    WIA.ImageFile     image           = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, WIA.FormatID.wiaFormatPNG, false);

                    if (image != null)
                    {
                        // save to  file
                        string fileName = SalvarPNG(image);
                        images.Add(new KeyValuePair <string, Image>(fileName, Image.FromFile(fileName)));
                    }

                    //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);
                        }
                    }
                }
                catch (Exception exc)
                {
                    int error = CodigoErroWIA(exc);
                    Mensagens.Add(DescricaoErro(exc));
                    if (error == WIA_ERROR_PAPER_EMPTY)
                    {
                        hasMorePages = false;
                    }
                    if (error == 0)
                    {
                        throw exc;
                    }
                }
                finally
                {
                    item = null;
                }
            }
            return(images);
        }
        public static Image ScanFile(string folderName, string fileName, ImageFormat imageFormat, bool overrideIfExists,
                                     ref string savedPath, ref string errorMessage)
        {
            WIA.ICommonDialog wiaCommonDialog = new WIA.CommonDialog();
            Device            device          = ConnectToScanner(GetScannerDevice());

            if (device == null)
            {
                return(null);
            }

            Image scannedImage = null;

            try
            {
                WIA.ImageFile image = null;
                WIA.Item      item  = device.Items[1] as WIA.Item;
                switch (imageFormat)
                {
                case ImageFormat.JPEG:
                    image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, JPEGFormat);
                    break;

                case ImageFormat.PNG:
                    image = (WIA.ImageFile)wiaCommonDialog.ShowTransfer(item, PNGFormat);
                    break;
                }

                if (image != null)
                {
                    string path     = FileManager.GetServerDirectoryPath(DB_ServerDirectory.ScanDirectory);
                    string fullPath = "";

                    string serverDirectorBaseFile =
                        FileManager.GetServerDirectoryName(DB_ServerDirectory.ScanDirectory);
                    if (!Directory.Exists(Path.Combine(path, serverDirectorBaseFile)))
                    {
                        Directory.CreateDirectory(Path.Combine(path, serverDirectorBaseFile));
                    }
                    if (!Directory.Exists(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName)))
                    {
                        Directory.CreateDirectory(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName));
                    }

                    switch (imageFormat)
                    {
                    case ImageFormat.JPEG:
                        fullPath = Path.Combine(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName), fileName + ".jpg");
                        break;

                    case ImageFormat.PNG:
                        fullPath = Path.Combine(Path.Combine(Path.Combine(path, serverDirectorBaseFile), folderName), fileName + ".png");
                        break;
                    }

                    if (File.Exists(Path.GetFullPath(fullPath)))
                    {
                        if (overrideIfExists)
                        {
                            File.Delete(Path.GetFullPath(fullPath));
                        }
                        else
                        {
                            errorMessage = "File is already exists";
                            return(null);
                        }
                    }

                    try
                    {
                        image.SaveFile(Path.GetFullPath(fullPath));
                    }
                    catch (Exception e)
                    {
                        errorMessage = "Network error";
                        return(null);
                    }

                    savedPath    = Path.GetFullPath(fullPath);
                    scannedImage = Image.FromFile(Path.GetFullPath(fullPath));
                }
            }
            catch (COMException e)
            {
                // Convert the error code to UINT
                uint errorCode = (uint)e.ErrorCode;

                // See the error codes
                if (errorCode == 0x80210006)
                {
                    errorMessage = "The scanner is busy or isn't ready";
                }
                else if (errorCode == 0x80210064)
                {
                    errorMessage = "The scanning process has been canceled.";
                }
                else if (errorCode == 0x8021000C)
                {
                    errorMessage = "There is an incorrect setting on the WIA device.";
                }
                else if (errorCode == 0x80210005)
                {
                    errorMessage = "The device is offline. Make sure the device is powered on and connected to the PC.";
                }
                else if (errorCode == 0x80210001)
                {
                    errorMessage = "An unknown error has occurred with the WIA device.";
                }
            }

            return(scannedImage);
        }
示例#19
0
        public static List<System.Drawing.Image> preScan(string scannerId)
        {
            List<System.Drawing.Image> images = new List<System.Drawing.Image>();
            bool hasMorePages = true;
            while (hasMorePages)
            {
                WIA.DeviceManager manager = new WIA.DeviceManager();
                WIA.Device device = null;

                foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                {
                    if (info.DeviceID == scannerId)
                    {
                        device = info.Connect();
                        break;
                    }
                }
                if (device == null)
                {
                    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);
                }
                WIA.Item item = device.Items[1] as WIA.Item;
                try
                {
                    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);
                    image = null;
                    // add file to output list
                    images.Add(System.Drawing.Image.FromFile(fileName));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                finally
                {
                    item = null;
                }
                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);
                    }
                }
            }
            return images;
        }
示例#20
0
文件: Adf.cs 项目: dadotnetkid/OFMIS
        /// <summary>
        /// Scan Page,
        /// </summary>
        /// <param name="wia">Connected Device</param>
        /// <param name="pageSize">Page Size. A4, A3, A2 Etc</param>
        /// <param name="RotatePage">Rotation of page while scanning</param>
        public void Scan(PageSize pageSize, bool rotatePage, int DPI, string filepath, bool useAdf, bool duplex)
        {
            int  pages        = 0;
            bool hasMorePages = false;

            WIA.CommonDialog WiaCommonDialog = new WIA.CommonDialog();

            try
            {
                do
                {
                    //Connect to Device
                    Device   wia  = Connect();
                    WIA.Item item = wia.Items[1] as WIA.Item;

                    //Setup ADF
                    if ((useAdf) || (duplex))
                    {
                        SetupADF(wia, duplex);
                    }

                    //Setup Page Size
                    SetupPageSize(wia, rotatePage, pageSize, DPI, item);

                    WIA.ImageFile imgFile        = null;
                    WIA.ImageFile imgFile_duplex = null; //if duplex is setup, this will be back page


                    imgFile = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);

                    //If duplex page, get back page now.
                    if (duplex)
                    {
                        imgFile_duplex = (ImageFile)WiaCommonDialog.ShowTransfer(item, wiaFormatJPEG, false);
                    }

                    string varImageFileName = filepath + "\\Scanned-" + pages.ToString() + ".jpg";
                    Delete_File(varImageFileName); //if file already exists. delete it.
                    imgFile.SaveFile(varImageFileName);

                    string varImageFileName_duplex;

                    if (duplex)
                    {
                        varImageFileName_duplex = filepath + "\\Scanned-" + pages++.ToString() + ".jpg";
                        Delete_File(varImageFileName_duplex); //if file already exists. delete it.
                        imgFile_duplex.SaveFile(varImageFileName);
                    }

                    //Check with scanner to see if there are more pages.
                    if (useAdf || duplex)
                    {
                        hasMorePages = HasMorePages(wia);
                        pages++; @
                    }
                } while (hasMorePages);
            }
            catch (COMException ex)
            {
            }
        }
示例#21
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images.</returns>
        public static List <Image> Scan(string scannerId)
        {
            List <Image> images       = new List <Image>();
            bool         hasMorePages = true;

            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 == scannerId)
                    {
                        // 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);
                }
                WIA.Item item = device.Items[1] as WIA.Item;
                //AdjustScannerSettings(scannnerItem, (int)nudRes.Value, 0, 0, (int)nudWidth.Value, (int)nudHeight.Value, 0, 0, cmbCMIndex);
                AdjustScannerSettings(item, 2);
                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);
                    image = null;
                    // add file to output list
                    images.Add(Image.FromFile(fileName));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                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);
                        }
                    }
                }
            }
            return(images);
        }
示例#22
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images.</returns>
        public static List <Image> Scan(string scannerId, int pages, WIAScanQuality quality, WIAPageSize pageSize, DocumentSource source)
        {
            List <Image> images       = new List <Image>();
            bool         hasMorePages = true;
            int          numbrPages   = pages;

            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 == scannerId)
                    {
                        // 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);
                }
                SetWIAProperty(device.Properties, WIA_DEVICE_PROPERTY_PAGES_ID, 1);
                SetWIAProperty(device.Properties, WIA_DEVICE_SOURCE_SELECT_ID, source);

                WIA.Item item = device.Items[1] as WIA.Item;

                // adjust the scan settings
                int dpi;
                int width_pixels;
                int height_pixels;
                switch (quality)
                {
                case WIAScanQuality.Final:
                    dpi = 300;
                    break;

                default:
                    throw new Exception("Unknown WIAScanQuality: " + quality.ToString());
                }
                switch (pageSize)
                {
                case WIAPageSize.A4:
                    width_pixels  = (int)(8.3f * dpi);
                    height_pixels = (int)(11.7f * dpi);
                    break;

                case WIAPageSize.Letter:
                    width_pixels  = (int)(8.5f * dpi);
                    height_pixels = (int)(11f * dpi);
                    break;

                case WIAPageSize.Legal:
                    width_pixels  = (int)(8.5f * dpi);
                    height_pixels = (int)(14f * dpi);
                    break;

                default:
                    throw new Exception("Unknown WIAPageSize: " + pageSize.ToString());
                }

                AdjustScannerSettings(item, dpi, 0, 0, width_pixels, height_pixels, 0, 0, 1);

                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);
                    image = null;
                    // add file to output list
                    images.Add(Image.FromFile(fileName));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                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);
                        }
                    }
                }
                numbrPages -= 1;
                if (numbrPages > 0)
                {
                    hasMorePages = true;
                }
                else
                {
                    hasMorePages = false;
                }
            }
            return(images);
        }
示例#23
0
        /// <summary>
        /// Use scanner to scan an image (scanner is selected by its unique id).
        /// </summary>
        /// <param name="scannerName"></param>
        /// <returns>Scanned images.</returns>
        public static List <Image> Scan(string scannerId)
        {
            List <Image> images       = new List <Image>();
            bool         hasMorePages = true;

            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 == scannerId)
                    {
                        // 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);
                }

                // Set color intent to greyscale if user requested it
                if (clrMode == Utils.ColorMode.Greyscale)
                {
                    Property prop = device.Items[1].Properties.get_Item("6146");
                    prop.set_Value(2); //4 is Black-white,gray is 2, color 1 (Color Intent)
                }

                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 = Utils.GetNextFileName(scannedDocumentsPath + "\\NumérisationSansTitre.bmp");
                    //File.Delete(fileName);
                    image.SaveFile(fileName);
                    image = null;
                    // add file to output list
                    images.Add(Image.FromFile(fileName));
                }
                catch (Exception exc)
                {
                    throw exc;
                }
                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);
                        }
                    }
                }
            }
            return(images);
        }