コード例 #1
0
ファイル: scanit.py プロジェクト: pmagwene/unscanny
def quick_scan(settings={}, test=False):
    """Make scan using first scanning device found by SANE driver.
    """
    # init and find devices
    sane.init()
    devices = sane.get_devices(localOnly=True)

    if test:
        devices = [("test", "SANE", "SANE", "SANE")]
        settings["source"] = "Flatbed"
        settings["test_picture"] = "Color pattern"
        settings["mode"] = "Color"
        settings["resolution"] = 75
        settings["depth"] = 8

    if not len(devices):
        return None
    dev_name = devices[0][0]

    # open scanner
    scanner = sane.open(dev_name)

    # set options
    if "mode" in settings:
        scanner.mode = settings["mode"]
    for (key, value) in settings.items():
        setattr(scanner, key, value)

    img = scanner.arr_scan()
    scanner.close()
    sane.exit()
    return img
コード例 #2
0
ファイル: scan.py プロジェクト: floatingshed/meats
def _init_sane(dialog):
    global s
    s = None
    start = time.time()
    version = sane.init()
    print('{} SANE version: {}, scanning devices...'.format(
        time.time() - start, version))

    available = sane.get_devices()
    print('{} Available devices = {}'.format(time.time() - start, available))

    if not available:
        print("NO DEVICES FOUND.")
        s = None
        dialog.statusLabel.config(
            text='Idle (no sane devices found) {:.1f} s'.format(time.time() -
                                                                start))
    else:
        if len(available) > 1:
            DeviceDialog(dialog, [row[0] for row in available],
                         start_time=start)
            return

        print('{} Opening first device: {}'.format(time.time() - start,
                                                   available[0]))
        open_start = time.time()
        s = sane.open(available[0][0])
        print('{} Device opened in {:.1f} s'.format(time.time() - start,
                                                    time.time() - open_start))
        dialog.statusLabel.config(
            text='Idle (sane loaded in {:.1f} s)'.format(time.time() - start))
コード例 #3
0
ファイル: scan.py プロジェクト: ahiscox/docdump
    def __init__(self):
        import sane

        sane.init()
        self.backup = False
        """ 
        When set to a fullpath, scans will be saved immediately to the path
        specified after scanning 
        """
        
        self.device = sane.get_devices()[0][0]
        self.sane = sane.open(self.device)
        self.sane.mode = 'Color'
        self.sane.source = 'ADF Duplex'
        self.sane.resolution = 300
        self.multi = self.sane.multi_scan()
        
        self.dd = time.strftime('%Y-%m-%d')
        """ Directory named after current date, used for self.backup """

        self.dt = time.strftime('%H-%M-%S')
        """ Directory named after current time, used for self.backup """ 

        self.cnt = 0
        """ Count used for files saved on backup """ 

	self.tmp = tempfile.mkdtemp()
	""" Temp directory used for scans """ 
コード例 #4
0
ファイル: app.py プロジェクト: Rouji/webscan
def scan():
    sane.init()
    devices = sane.get_devices(True)
    if not devices:
        sane.exit()
        return jsonify({'success': False, 'error': 'No scanner found.'}), 404
    try:
        dev = sane.open(devices[0][0])
        #param = dev.get_parameters()
        dev.mode = config.SCANNER_MODE
        dev.resolution = config.SCANNER_DPI
        dev.depth = config.SCANNER_BPP
        dev.start()
        im = dev.snap()
        dev.close()
    except Exception as ex:
        sane.exit()
        return jsonify({'success': False, 'error': 'Scanning failed. Scanner might not be ready or turned off.'}), 500
    if 'crop' in request.values:
        im = auto_crop(im)
    thumb = im.copy()
    thumb.thumbnail((config.THUMB_SIZE, config.THUMB_SIZE), Image.ANTIALIAS)
    id = rnd(20)
    scanned_images[id] = (
        pil_to_jpeg(im, config.JPEG_QUALITY),
        pil_to_jpeg(thumb, config.THUMB_QUALITY)
    )
    sane.exit()
    return jsonify({'success': True, 'id': id})
コード例 #5
0
def scan(device):
    try:
        scandev = sane.open(device)
        try:
            scandev.mode = 'Color24'
        except:
            debug('Unable to set scanner mode to "Color24".')
            try:
                scandev.mode = 'Color'
            except:
                debug('Unable to set scanner mode to "Color". Using default.')
        try:
            scandev.resolution = 300
        except:
            debug(
                'Unable to set scanner resolution to 300 DPI. Using default.')
        try:
            scandev.tl_x = 0
            scandev.tl_y = 0
            scandev.br_x = getScannerOption(scandev, 'br-x')[8][1]
            scandev.br_y = getScannerOption(scandev, 'br-y')[8][1]
        except:
            debug('Unable to set scan geometry. Using default.')
        result = scandev.scan()
        filename = tempfile.mktemp(suffix='.png')
        result.save(filename, 'PNG')
        scandev.close()
        return filename
    except (RuntimeError, sane._sane.error) as msgerr:
        return None
コード例 #6
0
ファイル: scanloop.py プロジェクト: darg0001/evoting-systems
 def __init__(self, duplex, height_in_mm, resolution):
     sane.init()
     errstring = ""
     s = sane.open(sane.get_devices()[0][0])
     if duplex:
         s.source = 'ADF Duplex'
     else:
         s.source = 'ADF Front'
     s.endorser = True
     s.endorser_string = '%08ud'
     s.page_height = height_in_mm
     s.br_y = height_in_mm
     s.mode = 'Color'
     s.resolution = resolution
     s.y_resolution = resolution
     # be ready to remove this if it does not properly set reported dpi
     s.swdeskew = 0 # software deskew might cause problems with our line recog
     # Gray at 140 took 3.1 sec
     # at 150 took 3.2 sec
     # at 200 took 4.0
     # at 220 took 5.1
     # at 240 took 3.2 sec
     # at 270 will not process properly
     # at 249 will not process properly
     self.s = s
     self.duplex = duplex
コード例 #7
0
 def __init__(self, duplex, height_in_mm, resolution):
     sane.init()
     s = sane.open(sane.get_devices()[0][0])
     if duplex:
         s.source = 'ADF Duplex'
     else:
         s.source = 'ADF Front'
     s.endorser = True
     s.endorser_string = '%08ud'
     s.page_height = height_in_mm
     s.br_y = height_in_mm
     s.mode = 'Color'
     s.resolution = resolution
     s.y_resolution = resolution
     # be ready to remove this if it does not properly set reported dpi
     s.swdeskew = 0  # software deskew might cause problems with our line recog
     # Gray at 140 took 3.1 sec
     # at 150 took 3.2 sec
     # at 200 took 4.0
     # at 220 took 5.1
     # at 240 took 3.2 sec
     # at 270 will not process properly
     # at 249 will not process properly
     self.s = s
     self.duplex = duplex
コード例 #8
0
ファイル: saneLib.py プロジェクト: cilybrother/autoScanner
    def setScanner(self, scannerName):
        """Connected to Scanner using Scanner Name

        Arguments:
        scannerName -- Name of Scanner return by getScanners()
        """
        self.scanner = sane.open(scannerName)
コード例 #9
0
ファイル: sane2MQTT.py プロジェクト: pgollor/sane2MQTT
    def on_setDevice(self, client, userdata, msg):
        devID = -1

        try:
            try:
                devID = int(msg.payload.decode())
            except ValueError:
                raise RuntimeError("Unknown device ID")
            if (len(self.devices) == 0):
                raise RuntimeError("No devices available.")
            if (len(self.devices) < (devID + 1)):
                raise RuntimeError("Invalid device ID.")
        except RuntimeError as e:
            self.logger.error(e.args)
            self.error(e.args)
            return
        self.device = sane.open(self.devices[devID][0])
        self.logger.info("using device: %s", self.device)

        # set optinos
        try:
            self.device.mode = self.options['mode']
            self.device.resolution = self.options['resolution']
            self.device.source = self.options['source']
        except:
            self.logger.error('Cannot set device options')
            self.error('Cannot set device options')
コード例 #10
0
ファイル: scan.py プロジェクト: ArchieT/optichess
 def __enter__(self):
     if self.savinr:
         fourcc_r = cv2.VideoWriter_fourcc(*'XVID')
         self.out_r = cv2.VideoWriter(self.saveraw,fourcc_r, 0.2, self.scanres)
     if self.savinm:
         fourcc_m = cv2.VideoWriter_fourcc(*'XVID')
         self.out_m = cv2.VideoWriter(self.savemod,fourcc_m, 0.2, self.scanres)
     self.zsejninita = sane.init()
     listaprzyp = {jest[0] for jest in sane.get_devices() if jest[1:]==self.scnr3tupl}
     if len(listaprzyp)==0: raise ScannerNotFound
     elif len(listaprzyp)==1: totenjest=listaprzyp[0]
     else:
         wybrano = False
         ktorytoje = list(totenjest)
         while not wybrano:
             try:
                 totenjest=ktorytoje[1+int(raw_input(''.join([
                     'Wybierz skaner: \n',
                     ''.join([''.join(['\t',str(nje),'. ',ktorytoje[nje],' \n']) for nje in range(len(ktorytoje))]),
                     'Podaj numer z listy: '])))]
                 wybrano = True
             except ValueError: pass
             except IndexError: pass
     self.skaner = sane.open(totenjest)
     self.skaner.mode = 'Gray'
     self.skaner.resolution = scanq
     return self
コード例 #11
0
 def show_scan_pdf_dialog(self, column):
     global device
     dialog = self.get_object("dialog1")
     result = dialog.run()
     dialog.hide()
     if result != Gtk.ResponseType.ACCEPT:
         return
     if device == None:
         device_address = self.get_object("combobox1").get_active_id()
         device = sane.open(device_address)
     document = device.scan()
     path = "/tmp/posting_pdf.pdf"
     document.save(path)
     f = open(path, 'rb')
     file_data = f.read()
     binary = psycopg2.Binary(file_data)
     f.close()
     self.cursor.execute(
         "UPDATE payroll.emp_pdf_archive "
         "SET archived = True "
         "WHERE employee_id = %s "
         "AND " + column + " IS NOT NULL", (self.employee_id, ))
     self.cursor.execute(
         "INSERT INTO payroll.emp_pdf_archive "
         "( " + column + ", employee_id, date_inserted) "
         "VALUES (%s, %s, %s)",
         (binary, self.employee_id, datetime.today()))
     DB.commit()
     self.populate_exemption_forms()
コード例 #12
0
ファイル: scanapp.py プロジェクト: wrishel/tevs_ancillary
 def reset(self):
     self.device.close()
     sane.exit()
     sane.init()
     devices = sane.get_devices()
     self.device = sane.open(devices[0][0])
     self.initialize()
コード例 #13
0
    def Open(self, idx):

        # out of index
        if idx < 0 or idx >= len(self.devlist):
            self.device = None
            return False

        try:
            self.device = sane.open(self.devlist[idx][0])
        except:
            self.device = None
            return False
        else:
            self.devname = self.devlist[idx][2]
            # retrieve option list
            self.options = self.device.get_options()
            # mode: must be exist in the list
            for item in self.options:
                if item[1] == 'mode':
                    self.modes = item[-1]
            # resolution: must be exist in the list
            for item in self.options:
                if item[1] == 'resolution':
                    self.resolutions = item[-1]
            # scan area:
            self.areas = ['Letter', 'Legal', 'A4', 'A5', 'A6']
            return True
コード例 #14
0
 def open_scanner(self, index):
     print("Open scanner", index)
     self.scanner = sane.open(self.scanners[index][0])
     self.scanner.depth = 16
     self.scanner.mode = "color"
     self.scanner.resolution = 300
     return self.scanner
コード例 #15
0
    def setScanner(self, scannerName):
        """Connected to Scanner using Scanner Name

        Arguments:
        scannerName -- Name of Scanner return by getScanners()
        """
        self.scanner = sane.open(scannerName)
コード例 #16
0
def executeScan(fileName):
    #
    # Change these for 16bit / grayscale scans
    #
    depth = 8
    mode = 'color'

    #
    # Initialize sane
    #
    ver = sane.init()
    print('SANE version:', ver)

    #
    # Get devices
    #
    devices = sane.get_devices()
    print('Available devices:', devices)

    #
    # Open first device
    #
    dev = sane.open(devices[0][0])

    #
    # Set some options
    #
    params = dev.get_parameters()
    print("device params", params)
    try:
        dev.depth = depth
    except:
        print('Cannot set depth, defaulting to %d' % params[3])

    try:
        dev.mode = mode
    except:
        print('Cannot set mode, defaulting to %s' % params[0])

    try:
        dev.br_x = 320.
        dev.br_y = 240.
    except:
        print('Cannot set scan area, using default')

    params = dev.get_parameters()
    print('Device parameters:', params)

    #
    # Start a scan and get and PIL.Image object
    #
    dev.start()
    im = dev.snap()
    im.save(fileName + '.png')

    #
    # Close the device
    #
    dev.close()
コード例 #17
0
ファイル: __init__.py プロジェクト: Coldarn/ImageScanner
    def scan(self, dpi=200):
        sane.init()
        scanner = sane.open(self._device)
        image = scanner.scan()
        scanner.close()
        sane.exit()

        return image
コード例 #18
0
ファイル: upload.py プロジェクト: robmyers/artworld-ethereum
def get_image():
    """Grab a single frame from the first webcam attached to the system"""
    webcam = sane.open('v4l:/dev/video0')
    webcam.mode='color'
    webcam.start()
    img = webcam.snap()
    webcam.close()
    return img
コード例 #19
0
ファイル: lib.py プロジェクト: ackalker/ocrfeeder
def scan(device):
    try:
        result = sane.open(device).scan()
        filename = tempfile.mktemp(suffix='.png')
        result.save(filename, 'PNG')
        return filename
    except (RuntimeError, sane._sane.error), msgerr:
        return None
コード例 #20
0
ファイル: lib.py プロジェクト: shalevy1/ocrfeeder
def scan(device):
    try:
        result = sane.open(device).scan()
        filename = tempfile.mktemp(suffix='.png')
        result.save(filename, 'PNG')
        return filename
    except (RuntimeError, sane._sane.error), msgerr:
        return None
コード例 #21
0
    def scan(self, dpi=200):
        sane.init()
        scanner = sane.open(self._device)
        image = scanner.scan()
        scanner.close()
        sane.exit()

        return image
コード例 #22
0
ファイル: saneAccess.py プロジェクト: julien-noblet/malodos
 def openScanner(self):
     """Connect to the scanner"""
     if self.selected is None: self.chooseSource()
     if self.selected is None : return
     try:
         scn = self.devices[self.selected][0]
         self.sourceData = sane.open(scn)
     except:
         self.sourceData = None
コード例 #23
0
 def setScanner(self,scanner):
     print 'setScanner',scanner
     if scanner != self.currentscanner:
         self.currentscanner = scanner
         self.scandev = sane.open(scanner)
         source = self.scandev['source']
         self.resolution = self.scandev.resolution
         self.emit(QtCore.SIGNAL('sourcelist(list)'),source.constraint)
         self.emit(QtCore.SIGNAL('papersize(QString)'),'Letter')
         self.scandev.close()
コード例 #24
0
def runScan(device,source,paper,dest):
    #print 'runScan',device,source,paper,dest
    sane.init()
    #print sane.get_devices()
    #print 'try to open scanner',device
    scandev = sane.open(device)
#   except:
#       'open scanner failed'
#       return -1

    #print 'set source', source
    if source == 'ADF':
        #print 'setting batch_scan'
        scandev.source = source
        scandev.batch_scan = 1
        scancount = 50
    else:
        scandev.source = source
        scandev.batch_scan = 0
        scancount = 1

    #set dpi to 200
    scandev.resolution = 200

    #calculate size and set x,y
    sizes = paperlist.paperlist[paper]
    #print 'setPaper',paper,sizes
#        print self.scandev.opt
    scandev.tl_x = 0
    scandev.tl_y = 0
    scandev.br_x = sizes[0]
    scandev.br_y = sizes[1]
    #print 'about to start scan'
#    s = raw_input()
    while scancount > 0:
        #print 'run',scancount
        try:
                scandev.start()
                scancount -= 1
        except:
                #traceback.print_exc()
                scancount = 0
                break

        #print 'scanning'
        img = scandev.snap()
        img = crop.autoCrop(img)
        filename = str(dest)+'/'+str(timeStamp())+'.png'
        img.save(filename,"PNG")
        #print 'closing scanner device'
        print filename
        #flush()

    scandev.close()
    return 0
コード例 #25
0
ファイル: scanfunctions.py プロジェクト: pmagwene/unscanny
def do_scanning(device_name, settings_dict):
    sane.init()
    scanner = sane.open(device_name)
    if "mode" in settings_dict:
        scanner.mode = settings_dict["mode"]
    for (key, value) in settings_dict.iteritems():
        setattr(scanner, key, value)
    imgarray = scanner.arr_scan()
    scanner.close()
    sane.exit()
    return imgarray
コード例 #26
0
def scan(device):
    try:
        scandev = sane.open(device)
        scandev.mode = 'color'
        scandev.resolution = 300
        result = scandev.scan()
        filename = tempfile.mktemp(suffix='.png')
        result.save(filename, 'PNG')
        scandev.close()
        return filename
    except (RuntimeError, sane._sane.error), msgerr:
        return None
コード例 #27
0
 def open(self, device_name):
     """
     Открыть устройство сканирования.
     @param device_name: Имя устройства сканирования.
     @return: Объект устройства сканирования.
     """
     try:
         self.scan_device_obj = sane.open(device_name)
         self.init_options_order()
     except:
         log.fatal(u'Ошибка открытия устройства сканирования <%s>' % device_name)
         self.scan_device_obj = None
     return self.scan_device_obj
コード例 #28
0
ファイル: scan.py プロジェクト: floatingshed/meats
 def choose(self):
     global s
     print('{} Choice made = {} (took {:.1f} s)'.format(
         time.time() - self.start_time, self.chosen.get(),
         time.time() - self.init_time))
     start_open = time.time()
     s = sane.open(self.chosen.get())
     stop_open = time.time()
     print('{} Device opened. (took {:.1f} s)'.format(
         stop_open - self.start_time, stop_open - start_open))
     total = self.init_time - self.start_time + time.time() - start_open
     self.scan_dialog.statusLabel.config(
         text='Idle (sane loaded in {:.1f} s)'.format(total))
     self.destroy()
コード例 #29
0
    def open(self, device_name):
        """
        Open scan device.

        :param device_name: The name of the scan device.
        :return: Scan device object.
        """
        try:
            self.scan_device_obj = sane.open(device_name)
            self.initOptionsOrder()
        except:
            log_func.fatal(u'Error opening scan device <%s>' % device_name)
            self.scan_device_obj = None
        return self.scan_device_obj
コード例 #30
0
ファイル: ServerWebSocket.py プロジェクト: arosh1909/template
def scanDoc():
    var = sane.init()

    devices = var.get_devices()
    print("Devices: " + devices)

    # Open first device
    dev = sane.open(devices[0][0])

    # Start a scan and get and PIL.Image object
    dev.start()
    im = dev.snap()
    im.save(FILE_NAME)
    dev.close()
コード例 #31
0
 def __init__(self):
     self.imgs = []
     self.settings = {}
     sane.init()
     try:
         for device in sane.get_devices():
             if device[3] == 'scanner':
                 self.scanner_device = sane.get_devices()[0][0]
         self.scanner = sane.open(self.scanner_device)
     except:
         self.settings['status'] = "NO SCANNER"
         print self.settings['status']
         self.scanner = None
         return None
     self.threadlock = thread.allocate_lock()
     self.settings['dpi'] = 100
     self.settings['scanner'] = self.scanner_device
     self.settings['page_height'] = int(25.4 * 11.0)
     self.settings['br_y'] = int(25.4 * 11.0)
     self.settings['page_width'] = int(25.4 * 8.5)
     self.settings['br_x'] = int(25.4 * 8.5)
     self.settings['duplex'] = True
     self.settings['imprinter'] = False
     self.settings['note'] = "No note."
     self.settings['status'] = "OK"
     self.settings['last'] = 0
     self.settings['last_processed'] = -1
     self.settings['status'] = "OK"
     self.scanner.resolution = self.settings['dpi']
     self.scanner.mode = 'color'
     if self.settings['duplex']:
         self.scanner.source = 'ADF Duplex'
     else:
         self.scanner.source = 'ADF Front'
     logging.info("Scanner is %s resolution %s mode %s source %s" %
                  (self.scanner_device, self.scanner.resolution,
                   self.scanner.mode, self.scanner.source))
     print "Scanner is %s resolution %s mode %s source %s" % (
         self.scanner_device, self.scanner.resolution, self.scanner.mode,
         self.scanner.source)
     self.scanner.endorser = True
     print "Set scanner endorser to True"
     #self.scanner.endorser_step = 1
     #print "Set scanner endorser_step to 1"
     #self.scanner.endorser_val = 11
     #print "Set scanner endorser_val to 11"
     for s in self.get_settings_splitbytype():
         print s
         print "---"
     return None
コード例 #32
0
ファイル: Scan.py プロジェクト: Rhydham/pdfscanner
    def __init__(self,*args,**kwargs):
        super(ScanWindow,self).__init__(*args, **kwargs)

        self.scannerSettings = {}
        self.images = []
        
        self.sane_version = sane.init()
        self.sane_devices = sane.get_devices()
        self.scanner = sane.open(self.sane_devices[0][0])
        self.initialiseScannerOptions(self.scanner)
        self.countLabel = None
        self.Bind(wx.EVT_CLOSE,self.OnClose)

        self.InitUI()
        self.Show(True)
コード例 #33
0
def main(model, results):
    sane.init()
    print("Loading scanner devices...")
    devices = sane.get_devices()
    if len(devices) == 0:
        print("No devices available.")
        return
    print(" Id Vendor                         Product")
    print("-" * 80)
    for idx, device in enumerate(devices):
        print(
            str(idx).rjust(3) + " " + device[1].ljust(30)[:30] + " " +
            device[2].ljust(46)[:46])
    while True:
        try:
            dev_id = int(input("Device ID: "))
            if not 0 <= dev_id < len(devices):
                print("Device id must be number between 0 and {}.".format(
                    len(devices) - 1))
            else:
                break
        except ValueError:
            print("Device id must be number between 0 and {}.".format(
                len(devices) - 1))
    try:
        device = sane.open(devices[dev_id][0])

        device.depth = 8
        device.mode = 'gray'
        device.resolution = 200

        # scan a page and to things...
        while True:
            while True:
                do_scan = input("Scan next page? [Y/n]  ")
                do_scan = do_scan.upper()
                if do_scan == 'Y' or do_scan == 'N' or do_scan == '':
                    break
            if do_scan == 'N':
                break

            device.start()
            im = device.snap()
            im.save('scanned.png')
            scan_page(im, model, results)
    finally:
        device.close()
    return
コード例 #34
0
ファイル: scanner.py プロジェクト: dmitrvk/smth
    def _get_device(self, device_name: str) -> sane.SaneDev:
        """Opens the device and sets the parameters according to config.

        Args:
            device_name:
                Name of a scanner device.

        Returns:
            A sane.SaneDev object representing a SANE device.
        """
        device = sane.open(device_name)
        device.format = 'jpeg'

        available_options = device.get_options()

        config_options = {}

        try:  # pylint: disable=too-many-nested-blocks
            config_options = {
                'mode': self._conf.scanner_mode,
                'resolution': self._conf.scanner_resolution,
            }

            for conf_option in config_options:
                if hasattr(device, conf_option):
                    for option in available_options:
                        value = config_options[conf_option]
                        allowed_values = option[8]

                        if option[1] == conf_option:
                            if value in allowed_values:
                                setattr(device, conf_option, value)
                            else:
                                message = ("Wrong value "
                                           f"'{value}' for option "
                                           f"'{conf_option}' "
                                           "in config file.\n"
                                           f"Allowed values: {allowed_values}")
                                self._callback.on_error(message)
                else:
                    message = "Scanner '{conf_option}' option cannot be set."
                    self._callback.on_error(message)

        except config.Error as exception:
            self._callback.on_error(str(exception))

        return device
コード例 #35
0
ファイル: scanner.py プロジェクト: lefred/centipede
def init_scanner(config):
    sane.init()
    logger.debug(sane.get_devices())
    scanners = [i[0] for i in sane.get_devices()  if i[2] == config.get("scanner", "model")]
    if not scanners:
        logger.error("Not able to find any scanner !")
        exit(1)
    scanner = sane.open(scanners[0])
    scanner.mode = config.get("scanner","mode")
    scanner.resolution = int(config.get("scanner", "resolution"))
    scanner.source = config.get("scanner", "source")
    if [True for i in config.items("input")  if i[0] == "type"]:
        logger.debug("Specifying format")
        scanner.br_x = float(config.get("input","size_x"))
        scanner.br_y = float(config.get("input","size_y"))
    scanner.swcrop = 1
    return scanner
コード例 #36
0
ファイル: scanner.py プロジェクト: iabsis/pyscanweb
 def getScannerList(self):
     scanOption = {}
     sane.init()
     scanners = sane.get_devices()
     for scanner in scanners:
         scan_open = sane.open(scanner[0])
         options = scan_open.get_options()
         scan_open.close()
         scanOption[scanner[0]] = {}
         for option in options:
             if option[1] == "mode":
                 scanOption[scanner[0]]["mode"] = option[8]
             elif option[1] == "source":
                 scanOption[scanner[0]]["source"] = option[8]
             elif option[1] == "resolution":
                 scanOption[scanner[0]]["resolution"] = {"min": option[8][0], "max": option[8][1], "step": option[8][2]}
     return scanOption
コード例 #37
0
	def write_info(self,towriteto):
		towriteto.write( '\n\nSANE version:\n'+str(sane.init()))
		devs = sane.get_devices()
		towriteto.write( '\n\nAvailable devices:\n'+str(devs))
		scanner = sane.open(devs[string.atoi(self.config.get('general','devicenumber'))][0])
		towriteto.write( '\n\nParameters of specified device:\n'+str(scanner.get_parameters()) )
		towriteto.write( '\n\nOptlist:\n')
		towriteto.write( str(scanner.optlist) )
		opts=scanner.get_options()
		towriteto.write( '\n\nActive options:\n')
		for x in opts:
			if self.option_is_active(x[1]):
				towriteto.write( str(x)+'\n' )
		towriteto.write( '\n\nInactive options:\n')
		for x in opts:
			if not self.option_is_active(x[1]):
				towriteto.write( str(x)+'\n' )
コード例 #38
0
 def scan_file_clicked(self, widget):
     if self.scanner == None:
         device_address = self.get_object("combobox2").get_active_id()
         self.scanner = sane.open(device_address)
     document = self.scanner.scan()
     misc_file_radiobutton = self.get_object("radiobutton6")
     if misc_file_radiobutton.get_active() == True:  #scan misc. file
         file_name = self.get_object("entry16").get_text()
         path = "/tmp/" + file_name + ".pdf"
         document.save(path)
         f = open(path, 'rb')
         data = f.read()
         binary = psycopg2.Binary(data)
         split_filename = path.split("/")
         name = split_filename[-1]
         name = re.sub(" ", "_", name)
         self.cursor.execute(
             "INSERT INTO files(file_data, contact_id, name) "
             "VALUES (%s, %s, %s)", (binary, self.contact_id, name))
     else:  #scan tax exemption
         exemption_selection = self.get_object('treeview-selection2')
         model, path = exemption_selection.get_selected_rows()
         customer_exemption_id = model[path][4]
         exemption_id = model[path][0]
         path = "/tmp/exemption.pdf"
         document.save(path)
         f = open(path, 'rb')
         data = f.read()
         binary = psycopg2.Binary(data)
         if customer_exemption_id == 0:
             self.cursor.execute(
                 "INSERT INTO customer_tax_exemptions "
                 "(pdf_data, customer_id, tax_rate_id, "
                 "pdf_available) "
                 "VALUES (%s, %s, %s, True) ",
                 (binary, self.contact_id, exemption_id))
         else:
             self.cursor.execute(
                 "UPDATE customer_tax_exemptions "
                 "SET (pdf_data, pdf_available) = "
                 "(%s, True) "
                 "WHERE id = %s", (binary, customer_exemption_id))
     f.close()
     self.db.commit()
     self.populate_tax_exemptions()
コード例 #39
0
ファイル: __init__.py プロジェクト: Coldarn/ImageScanner
    def _refresh(self):
        self._devices = []
        
        sane.init()
        devices = sane.get_devices()    
        for dev in devices:
            # Check if sane is able to open this device, if not just skip
            try:
                scanner = sane.open(dev[0])
                scanner.close()
            except:
                continue 
                                
            scanner_id = 'sane-%s' % len(self._devices)
            scanner = Scanner(scanner_id, dev[0], dev[1], dev[2], dev[3])
            self._devices.append(scanner)

        sane.exit()
コード例 #40
0
	def get_scanner(self):
		if (None == self.scanner) :
			t=time()
			print 'Initializing scanner ', sane.init(),
			print time()-t,'seconds'

			t=time()
			
			devs=sane.get_devices()
			print 'Fetching available devices took ',time()-t,'seconds'

			t=time()
			self.scanner=sane.open(devs[0][0])
			print 'Opening the first available device took ', time()-t,'seconds'

			return self.scanner
		else :
			return self.scanner
コード例 #41
0
ファイル: scanapp.py プロジェクト: wrishel/tevs_ancillary
    def __init__(self, device=None, sn=None, logger=None):
        if device is None:
            devices = sane.get_devices()
            try:
                self.device = sane.open(devices[0][0])
            except Exception as e:
                print "Could not open scanner"
        else:
            self.device = device
        self.sn = sn
        self.logger = logger

        self.img = None
        self.img1 = None
        self.img2 = None
        self.options_as_list = self.device.dev.get_options()
        self.options_as_list.sort(key=lambda a: a[0])
        self.initialize()
コード例 #42
0
    def _refresh(self):
        self._devices = []

        sane.init()
        devices = sane.get_devices()
        for dev in devices:
            # Check if sane is able to open this device, if not just skip
            try:
                scanner = sane.open(dev[0])
                scanner.close()
            except:
                continue

            scanner_id = 'sane-%s' % len(self._devices)
            scanner = Scanner(scanner_id, dev[0], dev[1], dev[2], dev[3])
            self._devices.append(scanner)

        sane.exit()
コード例 #43
0
ファイル: scannerselect.py プロジェクト: zdenop/lector
    def updateForm(self):
        """ Get data from scanner and present them in dialog
        """
        selectedScanner = self.sane_list[self.ui.combScanner.currentIndex()][0]
        saneScanner = sane.open(selectedScanner)

        # this is a list with a lot of info
        options = saneScanner.get_options()
        saneScanner.close()

        # extract just the info we want and put them in a dict
        dOptions = dict([(opt[1], opt[-1]) for opt in options])
        # print '\n'.join(["%s: %s" % (k, str(v)) for k, \
        #    v in sorted(dOptions.items())])

        #set max and min, if available
        try:
            self.ui.sbHeight.setMaximum(int(dOptions['br-y'][1]))
            self.ui.sbWidth.setMaximum(int(dOptions['br-x'][1]))
        except KeyError:
            ##TODO: if not available (a webcam?) do not use them in scanimage!
            pass

        #set resolution
        try:
            minimum = min(dOptions['resolution'])
            maximum = max(dOptions['resolution'])
        except KeyError:
            pass
        else:
            value = max(minimum, min(300, maximum))
            self.ui.sbResolution.setMaximum(maximum)
            self.ui.sbResolution.setMinimum(minimum)
            self.ui.sbResolution.setValue(value)

        #set color mode
        try:
            modes = dOptions['mode']
        except KeyError:
            pass
        else:
            combo = self.ui.combColor
            combo.clear()
            combo.addItems(modes)
コード例 #44
0
    def updateForm(self):
        """ Get data from scanner and present them in dialog
        """
        selectedScanner = self.sane_list[self.ui.combScanner.currentIndex()][0]
        saneScanner = sane.open(selectedScanner)

        # this is a list with a lot of info
        options = saneScanner.get_options()
        saneScanner.close()

        # extract just the info we want and put them in a dict
        dOptions = dict([(opt[1], opt[-1]) for opt in options])
        # print '\n'.join(["%s: %s" % (k, str(v)) for k, \
        #    v in sorted(dOptions.items())])

        #set max and min, if available
        try:
            self.ui.sbHeight.setMaximum(int(dOptions['br-y'][1]))
            self.ui.sbWidth.setMaximum(int(dOptions['br-x'][1]))
        except KeyError:
            ##TODO: if not available (a webcam?) do not use them in scanimage!
            pass

        #set resolution
        try:
            minimum = min(dOptions['resolution'])
            maximum = max(dOptions['resolution'])
        except KeyError:
            pass
        else:
            value = max(minimum, min(300, maximum))
            self.ui.sbResolution.setMaximum(maximum)
            self.ui.sbResolution.setMinimum(minimum)
            self.ui.sbResolution.setValue(value)

        #set color mode
        try:
            modes = dOptions['mode']
        except KeyError:
            pass
        else:
            combo = self.ui.combColor
            combo.clear()
            combo.addItems(modes)
コード例 #45
0
ファイル: sane_driver.py プロジェクト: vivekparat/lios-3
    def __init__(self,
                 device,
                 scanner_mode_switching,
                 resolution=300,
                 brightness=40,
                 scan_area=0):
        sane_version = sane.init()
        self.device_name = device[2]
        try:
            self.scanner = sane.open(device[0])
        except:
            print("####sane error!")
        else:
            #Brightness and Threshold
            self.light_parameter_state = False
            options = self.get_scanner_option('brightness')
            if options:
                self.light_parameter_state = True
                self.light_parameter = "brightness"
                try:
                    self.min = options[-1][0]
                    self.max = options[-1][1]
                except:
                    self.min = -100
                    self.max = 100

            options = self.get_scanner_option('threshold')
            if options:
                self.light_parameter_state = True
                self.light_parameter = "threshold"
                try:
                    self.min = options[-1][0]
                    self.max = options[-1][1]
                except:
                    self.min = 0
                    self.max = 255

            #Calling super constructor for inetialising brightness resolution and scan area
            super(DriverSane, self).__init__(scanner_mode_switching,device,resolution,\
            brightness,scan_area)
            if (not scanner_mode_switching):
                self.set_scan_mode("Color")
            self.brightness_multiplier = (self.max - self.min) / 100
            self.brightness_offset = self.min
コード例 #46
0
    def __init__(self,scanner=0,dpi=600,mode='Gray',depth=8):
        """ Scanner class with default parameters """
        sane.init()
        devices = sane.get_devices()
        try:
            device = devices[scanner]
        except IndexError:
            print 'No scanner found'
            self.scanner = False
            return
        
        #We just get the first one
        self.scanner = sane.open(device[0])
        #improve dpi
        self.scanner.resolution = dpi

        #there's other options to change 
        self.scanner.mode = mode
        self.scanner.depth = depth
コード例 #47
0
ファイル: tevsgui_scan.py プロジェクト: wrishel/tevs
    def __init__(self,
                 duplex,
                 height_in_mm,
                 resolution,
                 image_loc_fmt_string,
                 endorser=False):
        self.duplex = duplex
        self.height_in_mm = int(height_in_mm)
        self.resolution = int(resolution)
        self.image_loc_fmt_string = image_loc_fmt_string
        if endorser.startswith("T"):
            self.endorser = True
        else:
            self.endorser = False

        sane.init()
        print "Init"
        sys.stdout.flush()
        devlist = sane.get_devices()
        if len(devlist) < 1:
            print "No scanner found."
            sys.stdout.flush()
            sys.exit(0)
        self.s = sane.open(devlist[0][0])
        print "Devices"
        sys.stdout.flush()

        self.duplex = duplex
        if duplex.startswith("T"):
            self.s.source = 'ADF Duplex'
        else:
            self.s.source = 'ADF Front'
        try:
            self.s.endorser = self.endorser
            if self.s.endorser:
                self.s.endorser_string = '%08ud'
                try:
                    self.s.endorser_bits = 24
                except Exception, e:
                    print e
                    sys.stdout.flush()
        except AttributeError, e:
            print e
コード例 #48
0
ファイル: scan.py プロジェクト: Virako/fpinn
def scan(factura=None, cmr=None):
    print "scan"
    if factura:
        factura = factura.replace("/", "_")
        filename = "factura/%s.pdf" % (factura)
    if cmr:
        filename = "cmr/%s.pdf" % (cmr)
    if not filename:
        return -1

    sel_scan = select_scan()
    if not sel_scan:
        return -1
    scan = sane.open(sel_scan)
    scan.mode = 'color'
    scan.resolution = 150
    print "scannn"
    img = scan.scan()
    img.save(filename)
    return 1
コード例 #49
0
ファイル: scanner.py プロジェクト: rs/scanman
 def _open_first_device(self):
     devices = sane.get_devices()
     try:
         self.dev = sane.open(devices[0][0])
     except:
         self.dev = None
         return
     # Selects the scan source (ADF Front/ADF Back/ADF Duplex).
     self.dev.source = 'ADF Duplex'
     # Specifies the height of the media.
     self._set_option(7, 320.0)
     self._set_option(11, 320.0)
     # Selects the scan mode (e.g., lineart, monochrome, or color).
     self.dev.mode = 'color'
     # Sets the resolution of the scanned image (50..600dpi in steps of 1)).
     self.dev.resolution = 192
     # Controls the brightness of the acquired image. -127..127 (in steps of 1) [0]
     self.dev.brightness = 15
     # Controls the contrast of the acquired image. 0..255 (in steps of 1) [0]
     self.dev.contrast = 20
     # Set SDTC variance rate (sensitivity), 0 equals 127. 0..255 (in steps of 1) [0]
     self.dev.variance = 0
     # Collect a few mm of background on top side of scan, before paper
     # enters ADF, and increase maximum scan area beyond paper size, to allow
     # collection on remaining sides. May conflict with bgcolor option
     self.dev.overscan = 'Off'
     # Scanner detects paper lower edge. May confuse some frontends (bool).
     self.dev.ald = True
     # Request scanner to read pages quickly from ADF into internal memory (On/Off/Default).
     self.dev.buffermode = 'On'
     # Request scanner to grab next page from ADF (On/Off/Default).
     self.dev.prepick = 'On'
     # Request driver to rotate skewed pages digitally.
     self.dev.swdeskew = False
     # Maximum diameter of lone dots to remove from scan ([0..9] in steps of 1).
     self.dev.swdespeck = 0
     # Request driver to remove border from pages digitally.
     self.dev.swcrop = True
     # Request driver to discard pages with low percentage of dark pixels
     self.dev.swskip = 5
コード例 #50
0
    def __init__(self, 
                 duplex, 
                 height_in_mm, 
                 resolution, 
                 image_loc_fmt_string,
                 endorser=False):
        self.duplex = duplex
        self.height_in_mm = int(height_in_mm)
        self.resolution = int(resolution)
        self.image_loc_fmt_string = image_loc_fmt_string
        if endorser.startswith("T"):
            self.endorser = True
        else:
            self.endorser = False

        sane.init()
        print "Init"
        sys.stdout.flush()
        devlist = sane.get_devices()
        if len(devlist)<1:
            print "No scanner found."
            sys.stdout.flush()
            sys.exit(0)
        self.s = sane.open(devlist[0][0])
        print "Devices"
        sys.stdout.flush()

        self.duplex = duplex
        if duplex.startswith("T"):
            self.s.source = 'ADF Duplex'
        else:
            self.s.source = 'ADF Front'
        self.s.endorser = self.endorser
        if self.s.endorser:
            self.s.endorser_string = '%08ud'
            try:
                self.s.endorser_bits = 24
            except Exception, e:
                print e
                sys.stdout.flush()
コード例 #51
0
 def __init__(self):
     self.imgs = []
     self.settings = {}
     sane.init()
     try:
         for device in sane.get_devices():
             if device[3] == 'scanner':
                 self.scanner_device = sane.get_devices()[0][0]
         self.scanner = sane.open(self.scanner_device)
     except:
         self.settings['status'] = "NO SCANNER"
         print self.settings['status']
         self.scanner = None
         return None
     self.settings['dpi'] = 100
     self.settings['scanner'] = self.scanner_device
     self.settings['page_height'] = int(25.4 * 11.0)
     self.settings['br_y'] = int(25.4 * 11.0)
     self.settings['page_width'] = int(25.4 * 8.5)
     self.settings['br_x'] = int(25.4 * 8.5)
     self.settings['duplex'] = True
     self.settings['imprinter'] = False
     self.settings['note'] = "No note."
     self.settings['status'] = "OK"
     self.settings['last'] = 0
     self.settings['last_processed'] = -1
     self.settings['status'] = "OK"
     self.scanner.resolution = self.settings['dpi']
     self.scanner.mode = 'Color'
     if self.settings['duplex']:
         self.scanner.source = 'ADF Duplex'
     else:
         self.scanner.source = 'ADF Front'
     logging.info("Scanner is %s resolution %s mode %s source %s" %
                  (self.scanner_device, self.scanner.resolution,
                   self.scanner.mode, self.scanner.source))
     print "Scanner is %s resolution %s mode %s source %s" % (
         self.scanner_device, self.scanner.resolution, self.scanner.mode,
         self.scanner.source)
     return None
コード例 #52
0
ファイル: sane_driver.py プロジェクト: 2php/lios-3
	def __init__(self,device,scanner_mode_switching,resolution=300,brightness=40,scan_area=0):
		sane_version = sane.init()
		self.device_name = device[2];
		try:
			self.scanner = sane.open(device[0])
		except:
			print("####sane error!")
		else:
			#Brightness and Threshold
			self.light_parameter_state = False 
			options = self.get_scanner_option ('brightness')
			if options:
				self.light_parameter_state = True
				self.light_parameter = "brightness"
				try:
					self.min =  options[-1][0]
					self.max = options[-1][1]
				except:
					self.min = -100
					self.max = 100

			options = self.get_scanner_option ('threshold')
			if options:
				self.light_parameter_state = True
				self.light_parameter = "threshold"
				try:
					self.min =  options[-1][0]
					self.max = options[-1][1]
				except:
					self.min = 0
					self.max = 255
			
			#Calling super constructor for inetialising brightness resolution and scan area
			super(DriverSane, self).__init__(scanner_mode_switching,device,resolution,\
			brightness,scan_area)
			if(not scanner_mode_switching):
				self.set_scan_mode("Color")
			self.brightness_multiplier = (self.max - self.min)/100
			self.brightness_offset = self.min
コード例 #53
0
ファイル: __init__.py プロジェクト: joepie91/scantools
def init(**kwargs):
	global scanner
	
	sane.init()
	
	devices = {}
	i = 0
	
	print "Available devices:"
	
	for device in sane.get_devices():
		devices[i] = device[0]
		print "%d. [%s] %s %s" % (i, device[3], device[1], device[2])
		i += 1
	
	choice = int(raw_input("[?] What device would you like to use?  "))
	
	try:
		scanner = sane.open(devices[choice])
	except KeyError, e:
		print "You did not input a valid device ID."
		exit(1)
コード例 #54
0
ファイル: saneLib.py プロジェクト: cilybrother/autoScanner
    def getScanners(self):
        """Get available scanner from sane module
        """
        sane.init()
        devices = sane.get_devices()[0]

        scannerList = []
        for index, scannerName in enumerate(device):
            try:
                # Checking whether scanner is connected
                # Other would be working if first on is fine
                if index == 0:
                    scanner = sane.open(scannerName)
                    scanner.close()
                scannerList.append(scannerName)
            except Exception as e:
                # Scanner not connected but driver installed
                self.info = "Driver Installed but scanner not connected try restarting"

        if scannerList:
            return scannerList
        else:
            return None
コード例 #55
0
ファイル: SaneBackend.py プロジェクト: IMAGE-ET/dicomimport
	def scan(self, name=None):
		if not name:
			devices = self.listDevices()
			if not devices:
				self.emit( SIGNAL('error(int)'), Common.ScannerError.NoDeviceFound )
				return
			name = devices[0]

		try:
			print "Trying to open device: ", name
			source = sane.open( name )
			print "opened ", name
		except:
			print "error", name
			self.emit( SIGNAL('error(int)'), Common.ScannerError.CouldNotOpenDevice )
			return
			
		source.mode = 'color'
		source.resolution = self.resolution
		source.depth = 32

		print "Multi scan"
		iterator = source.multi_scan()
		print "yea scan"
		while True:
			try:
				image = ImageQt.ImageQt( iterator.next() )
				res = float(self.resolution) * 1000 / 25.4
				image.setDotsPerMeterX( res )
				image.setDotsPerMeterY( res )
				self.emit( SIGNAL('scanned(QImage)'), image )
			except StopIteration, e:
				# If StopIteration is raised, then there are no more images in 
				# the scanner
				self.emit( SIGNAL('finished()') )
				break
			except:
コード例 #56
0
ファイル: Camera.py プロジェクト: sriram911/SimpleCV
 def __init__(self, id = 0, properties = { "mode": "color"}):
     global _SANE_INIT
     import sane
     if not _SANE_INIT:
         try:
             sane.init()
             _SANE_INIT = True
         except:
             warn("Initializing pysane failed, do you have pysane installed?")
             return
 
     devices = sane.get_devices()
     if not len(devices):
         warn("Did not find a sane-compatable device")
         return
     
     self.usbid, self.manufacturer, self.model, self.kind = devices[id]
     
     self.device = sane.open(self.usbid)
     self.max_x = self.device.br_x
     self.max_y = self.device.br_y #save our extents for later
     
     for k, v in properties.items():
         setattr(self.device, k, v)
コード例 #57
0
 def run(self):
     self.usleep(10)
     self.device = sane.open(self.deviceName)
     self.options = self.device.get_options()
     qApp.postEvent(self.parent,OptionsReadyEvent(self.options,self.device))
コード例 #58
0
ファイル: demo_numarray.py プロジェクト: 1060460048/Pillow
from numarray import *
import sane
import Image

def toImage(arr):
    if arr.type().bytes == 1:
        # need to swap coordinates btw array and image (with [::-1])
        im = Image.frombytes('L', arr.shape[::-1], arr.tostring())
    else:
        arr_c = arr - arr.min()
        arr_c *= (255./arr_c.max())
        arr = arr_c.astype(UInt8)
        # need to swap coordinates btw array and image (with [::-1])
        im = Image.frombytes('L', arr.shape[::-1], arr.tostring())
    return im

print('SANE version:', sane.init())
print('Available devices=', sane.get_devices())

s = sane.open(sane.get_devices()[0][0])

# Set scan parameters
s.mode = 'gray'
s.br_x=320. ; s.br_y=240.

print('Device parameters:', s.get_parameters())

s.depth=16
arr16 = s.arr_scan()
toImage(arr16).show()
コード例 #59
0
	def do_GET(self):
		if self.path == '/favicon.ico': #reroute annoying favicon requests so we don't have to send 404s
			self.path = '/style/images/tmp.ico'
	
		try:	
			#If the path contains a ? then we should parse it and scan and stuff --> http://www.faqts.com/knowledge_base/view.phtml/aid/4373		
			if self.path.find('?')!=-1:
				pathlist, values = self.urlParse(self.path)
				
				#Handle a refresh of the preview
				if values['button'] == 'snap':
					self.update_preview()
					self.path=extbase+'/demo.html'
				#Handle a scan
				elif values['button'] == 'scan':
					self.send_response(200)
					self.send_header('Content-type','image/png')
					self.end_headers()
					
					scanner=self.get_scanner()
					
					
					if values['imgtype'] == 'BW':
						scanner.mode='Lineart'
					elif values['imgtype'] == 'GRAY':
						scanner.mode='Gray'
					else:
						scanner.mode='Color'
					
					if values['resolution'] == 'OTHER':
						scanner.resolution=string.atof(values['custom_resolution'])
					else:
						scanner.resolution=string.atof(values['resolution'])
					
					#Translate the pixel locations in to realworld coordinates (in to mm)
					scanner.tl_x=string.atof(values['left']) * inchinmm / previewres 
					scanner.tl_y=string.atof(values['top']) * inchinmm / previewres
					scanner.br_x=scanner.tl_x + string.atoi(values['width']) * inchinmm / previewres 
					scanner.br_y=scanner.tl_y + string.atoi(values['height']) * inchinmm / previewres
					
					self.scan_and_save(self.wfile, values['filetype'])
					return
				#Error, print some debugging info
				else:
					self.send_response(200)
					self.send_header('Content-type','text/html')
					self.end_headers()
					self.wfile.write("<html><head/><body>Error. Form has no button value. ",str(values),"</body></html>")
					return

			#Snap a preview image and send it directly to the browser
			if self.path==extbase+'/snap':
				self.send_response(200)
				self.send_header('Content-type','image/png')
				self.end_headers()

				scanner=self.get_scanner()

				scanner.preview=True
				scanner.quality_cal=False
				scanner.depth=4
				scanner.resolution=previewres

				self.scan_and_save(self.wfile, 'PNG')

			#Do a scan and return the image directly to the browser
			elif self.path==extbase+'/scan':
				self.send_response(200)
				self.send_header('Content-type','image/png')
				self.end_headers()
				
				scanner=self.get_scanner()
				
				scanner.resolution=300.0
				
				self.scan_and_save(self.wfile, 'PNG')
				
			#FIXME!
#			elif self.path.endswith('.xhtml'):
#				f=open(basepath+self.path)
#				self.send_response(200)
#				self.send_header('Content-type','text/html')
#				self.end_headers()
#				
#				reader = Sax2.Reader()
#				doc=reader.fromStream(f)
#				PrettyPrint(doc,self.wfile)
#				
#				f.close()
#			
			#Used for debugging. Displays info about scanner.
			elif self.path==extbase+'/info':
				self.send_response(200)
				self.send_header('Conent-type','text/plain')
				self.end_headers()
				self.wfile.write( '\n\nSANE version:\n'+ str(sane.init()))
				devs = sane.get_devices()
				self.wfile.write( '\n\nAvailable devices:\n'+str(devs))
				scanner = sane.open(devs[0][0])
				self.wfile.write( '\n\nParameters of first device:\n'+str(scanner.get_parameters()) )
				self.wfile.write( '\n\nOptions:\n'+str(scanner.get_options()) )
			
			#We replace chair.jpg with the preview file.
			elif self.path==extbase+'/chair.jpg':
				f=open(previewfile)
				self.send_response(200)
				self.send_header('Content-type','image/png')
				self.end_headers()
				self.wfile.write(f.read())
				f.close()
			#If nothing special was aksed, just serve the file of the specified name
			else:
				print basepath+self.path
				f=open(basepath+self.path)
				self.send_response(200)
				
				if self.getContentType() == None:
					#Let's not serve unknown stuff
					self.send_header('Content-type','text/plain')
					self.end_headers()
					f.close()
					return
				else:
					self.send_header('Content-type',self.getContentType())
					
				self.end_headers()
				self.wfile.write(f.read())
				f.close()
		#If we cant open the file (=can't find the file) we send a 404
		except IOError:
			self.send_error(404, 'IOError')