Ejemplo n.º 1
0
def importFile(self, file, REQUEST, handler):

    # Get filename.
    if isinstance(file, ZPublisher.HTTPRequest.FileUpload):
        filename = file.filename
    else:
        filename = file.name
    standard.writeBlock(self, '[importFile]: filename=' + filename)

    # Create temporary folder.
    folder = tempfile.mktemp()
    os.mkdir(folder)

    # Save to temporary file.
    filename = _fileutil.getOSPath(
        '%s/%s' % (folder, _fileutil.extractFilename(filename)))
    _fileutil.exportObj(file, filename)

    # Import ZEXP-file.
    if _fileutil.extractFileExt(filename) == 'zexp':
        ob = self._importObjectFromFile(filename, verify=0)
        # Remove temporary files.
        _fileutil.remove(folder, deep=1)
        # Refresh zcatalog_index
        standard.triggerEvent(self, '*.onImportObjEvt')
        return ob

    # Find XML-file.
    if _fileutil.extractFileExt(filename) == 'zip':
        _fileutil.extractZipArchive(filename)
        filename = None
        for deep in [0, 1]:
            for ext in ['xml', 'htm', 'html']:
                if filename is None:
                    filename = _fileutil.findExtension(ext, folder, deep)
            break
        if filename is None:
            raise zExceptions.InternalError('XML-File not found!')

    # Import Filter.
    if REQUEST.get('filter', '') in self.getFilterManager().getFilterIds():
        filename = _filtermanager.importFilter(self, filename,
                                               REQUEST.get('filter', ''),
                                               REQUEST)

    # Import XML-file.
    standard.writeBlock(self, '[importFile]: filename=' + filename)
    f = standard.pyopen(filename, 'r', encoding='utf-8')
    ob = handler(self, f)
    f.close()

    # Remove temporary files.
    _fileutil.remove(folder, deep=1)

    # Return imported object.
    return ob
Ejemplo n.º 2
0
def resize(img, size, mode='resize', sffx='_thumbnail', qual=75):
  """
  Resize image.
  @rtype: C{MyImage}
  """
  from PIL import Image, ImageFile
  ImageFile.LOAD_TRUNCATED_IMAGES = True
  
  # Save image in temp-folder
  context = img.aq_parent
  tempfolder = tempfile.mktemp()
  filepath = _fileutil.getOSPath('%s/%s'%(tempfolder, img.filename))
  _fileutil.exportObj(img, filepath)
  
  # Resize SVG
  svg_dim = svgutil.get_dimensions(img)
  if svg_dim is not None:
    img = svgutil.set_dimensions(img,size)
    f = open(filepath, 'wb')
    f.write(img.getData())
    f.close()
  
  # Resize image
  else:
    im = Image.open(filepath)
    im = im.convert('RGB')
    maxdim = max(list(size))
    if mode == 'thumbnail':
      try:
        im.thumbnail((maxdim, maxdim), Image.ANTIALIAS)
      except:
        im.thumbnail((maxdim, maxdim))
    elif mode == 'resize':
      try:
        im = im.resize(size, Image.ANTIALIAS)
      except:
        im = im.resize(size)
    elif mode == 'square':
      try:
        width, height = im.size
        dst_width, dst_height = maxdim, maxdim
        if width > height:
          delta = width - height
          left = int(delta/2)
          upper = 0
          right = height + left
          lower = height
        else:
          delta = height - width
          left = 0
          upper = int(delta/2)
          right = width
          lower = width + upper
        im = im.crop(( left, upper, right, lower))
        im = im.resize((dst_width, dst_height), Image.ANTIALIAS)
      except:
        im.resize(size)
    im.convert('RGB').save(filepath, "JPEG", quality=qual, optimize=True)
  
  # Read resized image from file-system
  f = open(filepath, 'rb')
  result_data = f.read()
  f.close()
  
  # Remove temp-folder and images
  _fileutil.remove(tempfolder, deep=1)
  
  thumb_sffx = str(sffx)
  getfilename = _fileutil.extractFilename(filepath).split('.')
  filename = getfilename[0:-1]
  filename = ".".join(filename)
  filename = filename.replace('.', '_')
  extension = _fileutil.extractFileExt(filepath)
  result_filename = filename + thumb_sffx + '.' + extension
  result = {'data':result_data,'filename':result_filename}
  
  # Returns resulting image
  image = standard.ImageFromData(context, result['data'], result['filename'])
  return image