使用WIA自动进纸器扫描仪扫描失败,第二页 [英] Scanning with WIA automatic feeder scanner fails for second page

查看:56
本文介绍了使用WIA自动进纸器扫描仪扫描失败,第二页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用具有自动进纸器的扫描仪扫描多页.目前,我的代码非常简单:

I'm trying to scan multiple pages using a scanner which has an automatic feeder. My code is very simple at the moment:

WIA.CommonDialog dialog = new WIA.CommonDialog();
WIA.Device device = dialog.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType);
WIA.Items items = dialog.ShowSelectItems(device);
foreach (WIA.Item item in items)
{
    while (true)
    {
        try
        {
            WIA.ImageFile image = (WIA.ImageFile)dialog.ShowTransfer(item);
            if (image != null && image.FileData != null)
            {
                dynamic binaryData = image.FileData.get_BinaryData();
                if (binaryData is byte[])
                    using (MemoryStream stream = new MemoryStream(binaryData))
                    using (Bitmap bitmap = (Bitmap)Bitmap.FromStream(stream))
                    {
                        bitmap.Save(@"C:\Temp\scan.jpg", ImageFormat.Jpeg);
                    }
            }
        }
        catch (COMException)
        {
            break;
        }
    }
}

我尝试查询 WIA_DPS_DOCUMENT_HANDLING_STATUS 属性以查看供稿器中是否有任何可用页面,但是该页面始终返回1,所以我会捕获COM异常,如果得到 WIA_ERROR_PAPER_EMPTY ,我知道文档进纸器为空.

I tried querying the WIA_DPS_DOCUMENT_HANDLING_STATUS property to see if there are any pages available in the feeder, but that always returns 1, so instead I'm catching a COM exception an if I get the WIA_ERROR_PAPER_EMPTY, I know that the document feeder is empty.

麻烦的是,这段代码仅扫描第一页,当再次调用 dialog.ShowTransfer 方法时,我得到了 E_FAIL HResult的异常,我可以不再扫描任何页面.奇怪的是,当我在调试器中逐步执行此代码时,一切正常,并对所有页面进行了扫描.

The trouble is that this code only scans the first page, when the dialog.ShowTransfer method is called again, I get an exception with and E_FAIL HResult and I can't scan any more pages. Strangely enough, when I step through this code in the debugger, everything works fine and all pages are scanned.

我尝试通过执行 Marshal.ReleaseComObject(image) image = null 释放图像对象,但这没有帮助.这个问题的建议也没有.我做错了什么导致这些错误吗?

I tried freeing up the image object by doing Marshal.ReleaseComObject(image) and image = null, but that didn't help. Neither did the suggestions from this question. Is there anything I'm doing wrong that's causing these errors?

我无法为此找到一个好的解决方案.进纸器准备扫描下一页时,扫描仪不断抛出 E_FAIL ,这需要花费几秒钟的时间(这不是非常快的扫描仪).因此,我添加了一个循环以尝试10秒钟,这是我不喜欢的解决方案,但似乎可行.

I wasn't able to find a good solution for this. The scanner keeps throwing E_FAIL while the feeder is getting ready to scan the next page, which takes a couple of seconds (it is not a very fast scanner). So, I added a loop to keep trying for 10 seconds, which is a solution that I don't like, but it seems to work.

这似乎与打印机的WIA驱动程序有关.我尝试过使用其他品牌的打印机,但根本没有这个问题.

EDIT 2: This seems to be an issue with the printer's WIA driver. I tried this with a different brand printer and it didn't have this problem at all.

推荐答案

我正在做同样的事情,并尝试使用您的代码以及以下示例中的代码:

I'm working on the same thing, and tried to use your code and code from this example: http://www.codeproject.com/Tips/792316/WIA-Scanner-in-Csharp-Windows-Forms

我在hp scanjet 5590上测试了您的代码,即使我在调试器中单步执行代码,它也只能获得一张图像.在第二个调用对话框上,ShowTransfer引发ArgumentException,并显示消息值不在预期范围内".我设法通过重置图像"和对话框"对象并设置一个显式的传输格式ID使其起作用.同样,您的代码将图像写入了相同的文件.如果将其应用于您的代码,这对我有用:

I tested your code on hp scanjet 5590, it only manages to get one image, even when I step through the code in debugger. On second call dialog.ShowTransfer throws ArgumentException with message "Value does not fall within the expected range." I managed to make it work by resetting 'image' and 'dialog' objects and also setting an explicit transfer format ID. Also your code wrote images to the same file. Here is what worked for me if applied to your code:

WIA.CommonDialog dialog = new WIA.CommonDialog();
        WIA.Device device = dialog.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType);
        WIA.Items items = dialog.ShowSelectItems(device);
        foreach (WIA.Item item in items)
        {
            while (true)
            {
                WIA.ImageFile image = null;
                try
                {
                    dialog = new WIA.CommonDialog();
                    image = (WIA.ImageFile)dialog.ShowTransfer(item,"{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}", false);
                    if (image != null && image.FileData != null)
                    {
                        dynamic binaryData = image.FileData.get_BinaryData();
                        if (binaryData is byte[])
                            using (MemoryStream stream = new MemoryStream(binaryData))
                            using (Bitmap bitmap = (Bitmap) Bitmap.FromStream(stream))
                            {
                                bitmap.Save(String.Format(@"C:\Temp\scan{0}.jpg", Path.GetRandomFileName()),
                                    ImageFormat.Jpeg);
                            }
                    }
                }
                catch (COMException)
                {
                    break;
                }
                finally
                {
                    if (image != null)
                        Marshal.FinalReleaseComObject(image);
                }
            }
        }

该CodeProject示例在我的硬件上也失败了,但是相同的修复程序有所帮​​助.如果上面的代码仍然不适合您,请尝试一下,将原来的Scan方法替换为:

That CodeProject example failed on my hardware as well, but the same fixes helped. Try it if the code above still doesn't work for you, replace the original Scan method by this:

    public static List<Image> Scan(string scannerId)
    {
        List<Image> images = new List<Image>();

        // 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 = null;
        WIA.CommonDialog dialog = new WIA.CommonDialog();
        WIA.Items items = dialog.ShowSelectItems(device);
        if (items == null)
            return images;

        item = items[1];

        bool hasMorePages = true;
        while (hasMorePages)
        {
            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);
                try
                {
                    Marshal.FinalReleaseComObject(image);
                }
                finally
                {
                    image = null;
                }
                // add file to output list
                images.Add(Image.FromFile(fileName));
            }
            finally
            {
                //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;
    }

也用此替换btn_scan_Click方法:

Also replace btn_scan_Click method by this:

    private void btn_scan_Click(object sender, EventArgs e)
    {

        try
        {
            //get list of devices available
            List<string> devices = WIAScanner.GetDevices();
            List<Image> images = null;

            //check if device is not available
            if (devices.Count == 0)
            {
                MessageBox.Show("You do not have any WIA devices.");
                this.Close();
            }
            else
            {
                if (devices.Count == 1)
                {
                    images = WIAScanner.Scan(devices[0]);
                }
                else
                {
                    images = WIAScanner.Scan();
                }
            }
            //get images from scanner
            foreach (Image image in images)
            {
                var path = String.Format(@"C:\Temp\scan{0}_{1}.jpg", DateTime.Now.ToString("yyyy-MM-dd HHmmss"), Path.GetRandomFileName());
                image.Save(path, ImageFormat.Jpeg);
            }
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }
    }

这篇关于使用WIA自动进纸器扫描仪扫描失败,第二页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆