Example #1
0
    def save_screenshot(self, path):
        """
        Get and save screenshot of element or window.
        :param path: path to save the screenshot file; eg. screen.png, /path/to/image.png
        """
        from atomac.ldtpd.generic import Generic
        from cStringIO import StringIO
        from PIL import Image

        # capture the app window screen and load it as Image using PIL
        generic = Generic()
        image_base64_string = generic.imagecapture(
            window_name=self.app.windows()[0].AXTitle)
        image = StringIO(image_base64_string.decode('base64'))
        image = Image.open(image)

        # get app window position
        app_pos_x, app_pos_y = self.app.windows()[0].AXPosition
        # get element position and size
        elem_pos_x, elem_pos_y = self.get_element().AXPosition
        elem_size_x, elem_size_y = self.get_element().AXSize
        # count element's relative position
        pos_x = elem_pos_x - app_pos_x
        pos_y = elem_pos_y - app_pos_y
        # crop and save the image
        image = image.crop((int(pos_x), int(pos_y), int(pos_x + elem_size_x),
                            int(pos_y + elem_size_y)))
        image.save(path)
Example #2
0
def scaleImage(image,
               width=None,
               height=None,
               direction='down',
               quality=88,
               result=None):
    """Scale a given image.

    Scale the given image data to another size and return the result as a
    string or optionally write into the file-like `result` object.

    The `image` parameter can either be the raw image data (i.e. a `str`
    instance) or an open file.

    The `quality` parameter can be used to set the quality of the resulting
    image scales.

    The return value is a tuple with the new image, the image format and a
    size-tuple. Optionally a file-like object ca be given as the `result`
    parameter, in which the generated image scale will be stored.

    The `width`, `height` and `direction` parameters will be passed to
    :meth:`scalePILImage`, which performs the actual scaling.
    """
    if isinstance(image, str):
        image = StringIO(image)

    try:
        image = PIL.Image.open(image)
    except IOError as e:
        logger.warning('Error opening image: ' + str(e))
        return None

    try:
        image.load()
    except Exception as e:
        logger.warning('Error loading image: ' + str(e))
        return None

    # When we create a new image during scaling we loose the format
    # information, so remember it.
    format = image.format
    if not format == 'PNG':
        format = 'JPEG'

    image = scalePILImage(image, width, height, direction)

    if result is None:
        result = StringIO()
        image.save(result, format, quality=quality, optimize=True)
        result = result.getvalue()
    else:
        image.save(result, format, quality=quality, optimize=True)
        result.seek(0)

    return result, format, image.size
Example #3
0
def scaleImage(image, width=None, height=None, direction="down",
               quality=88, result=None):
    """Scale the given image data to another size and return the result
    as a string or optionally write in to the file-like `result` object.

    The `image` parameter can either be the raw image data (ie a `str`
    instance) or an open file.

    The `quality` parameter can be used to set the quality of the
    resulting image scales.

    The return value is a tuple with the new image, the image format and
    a size-tuple.  Optionally a file-like object can be given as the
    `result` parameter, in which the generated image scale will be stored.

    The `width`, `height`, `direction` parameters will be passed to
    :meth:`scalePILImage`, which performs the actual scaling.
    """
    if isinstance(image, str):
        image = StringIO(image)
    image = PIL.Image.open(image)

    # When we create a new image during scaling we loose the format
    # information, so remember it here.
    format = image.format
    if not format == 'PNG':
        format = 'JPEG'

    image = scalePILImage(image, width, height, direction)

    if result is None:
        result = StringIO()
        image.save(
            result,
            format,
            quality=quality,
            optimize=True,
            progressive=True)
        result = result.getvalue()
    else:
        image.save(
            result,
            format,
            quality=quality,
            optimize=True,
            progressive=True)
        result.seek(0)

    return result, format, image.size
Example #4
0
def get_image(width, height):
    quantity = database.picture.find({}).count()
    if quantity == 0:
        return 'No data'
    random_value = random.randrange(0, quantity)
    photo = database.picture.find({})[random_value]
    object_id = photo['picture_id']
    _file = fs.get(object_id)

    im = StringIO()
    im.write(_file.read())
    im.seek(0)
    im = Image.open(im)
    size = (width, height)
    im = im.resize(size, Image.ANTIALIAS)
    im_io = StringIO()
    format_file = _file.name.split('.')[1]
    if format_file == 'jpg':
        format_file = 'jpeg'
    im.save(im_io, format_file, quality=50)
    im_io.seek(0)

    return send_file(im_io, mimetype='image/jpeg')
Example #5
0
def get_image(width, height):
    quantity = database.picture.find({}).count()
    if quantity == 0:
        return 'No data'
    random_value = random.randrange(0, quantity)
    photo = database.picture.find({})[random_value]
    object_id = photo['picture_id']
    _file = fs.get(object_id)

    im = StringIO()
    im.write(_file.read())
    im.seek(0)
    im = Image.open(im)
    size = (width, height)
    im = im.resize(size, Image.ANTIALIAS)
    im_io = StringIO()
    format_file = _file.name.split('.')[1]
    if format_file == 'jpg':
        format_file = 'jpeg'
    im.save(im_io, format_file, quality=50)
    im_io.seek(0)

    return send_file(im_io, mimetype='image/jpeg')
Example #6
0
def scaleImage(image,
               width=None,
               height=None,
               direction='down',
               quality=88,
               result=None):
    """Scale the given image data to another size and return the result
    as a string or optionally write in to the file-like `result` object.

    The `image` parameter can either be the raw image data (ie a `str`
    instance) or an open file.

    The `quality` parameter can be used to set the quality of the
    resulting image scales.

    The return value is a tuple with the new image, the image format and
    a size-tuple.  Optionally a file-like object can be given as the
    `result` parameter, in which the generated image scale will be stored.

    The `width`, `height`, `direction` parameters will be passed to
    :meth:`scalePILImage`, which performs the actual scaling.

    The generated image is a JPEG image, unless the original is a PNG or GIF
    image. This is needed to make sure alpha channel information is
    not lost, which JPEG does not support.
    """
    if isinstance(image, (bytes, str)):
        image = StringIO(image)
    image = PIL.Image.open(image)
    # When we create a new image during scaling we loose the format
    # information, so remember it here.
    format_ = image.format
    if format_ not in ('PNG', 'GIF'):
        # Always generate JPEG, except if format is PNG or GIF.
        format_ = 'JPEG'
    elif format_ == 'GIF':
        # GIF scaled looks better if we have 8-bit alpha and no palette
        format_ = 'PNG'

    icc_profile = image.info.get('icc_profile')
    image = scalePILImage(image, width, height, direction)

    # convert to simpler mode if possible
    colors = image.getcolors(maxcolors=256)
    if image.mode not in ('P', 'L') and colors:
        if format_ == 'JPEG':
            # check if it's all grey
            if all(rgb[0] == rgb[1] == rgb[2] for c, rgb in colors):
                image = image.convert('L')
        elif format_ == 'PNG':
            image = image.convert('P')

    if image.mode == 'RGBA' and format_ == 'JPEG':
        extrema = dict(zip(image.getbands(), image.getextrema()))
        if extrema.get('A') == (255, 255):
            # no alpha used, just change the mode, which causes the alpha band
            # to be dropped on save
            image.mode = "RGB"
        else:
            # switch to PNG, which supports alpha
            format_ = 'PNG'

    new_result = False

    if result is None:
        result = StringIO()
        new_result = True

    image.save(result,
               format_,
               quality=quality,
               optimize=True,
               progressive=True,
               icc_profile=icc_profile)

    if new_result:
        result = result.getvalue()
    else:
        result.seek(0)

    return result, format_, image.size
Example #7
0
def scaleImage(image, width=None, height=None, direction="down",
        quality=88, result=None):
    """Scale an image to another size.

    The generated image is a JPEG image, unless the original is a PNG
    image. This is needed to make sure alpha channel information is
    not lost, which JPEG does not support.

    Three different scaling options are supported:
    
    * `up` scaling scales the smallest dimension up to the required size
      and scrops the other dimension if needed.
    * `down` scaling starts by scaling the largest dimension to the required
      size and scrops the other dimension if needed.
    * `thumbnail` scales to the requested dimensions without cropping. The
      resulting image may have a different size than requested. This option
      requires both width and height to be specified. `keep` is accepted as
      an alternative spelling for this option, but its use is deprecated.

    The `image` parameter can either be the raw image data (ie a `str`
    instance) or an open file.

    The `quality` parameter can be used to set the quality of the
    resulting image scales.

    The return value is a tuple with the new image, the image format and
    a size-tuple.  Optionally a file-like object can be given as the
    `result` parameter, in which the generated image scale will be stored.
    """
    if direction=="keep":
        direction="thumbnail"

    if direction=="thumbnail" and not (width and height):
        raise ValueError("Thumbnailing requires both width and height to be specified")
    elif width is None and height is None:
        raise ValueError("Either width or height need to be given")

    if isinstance(image, str):
        image=StringIO(image)
    image=PIL.Image.open(image)

    if image.mode=="1":
        # Convert black&white to grayscale
        image=image.convert("L")
    elif image.mode=="P":
        # Convert palette based images to 3x8bit+alpha
        image=image.convert("RGBA")
    elif image.mode=="CMYK":
        # Convert CMYK to RGB, allowing for web previews of print images
        image=image.convert("RGB")

    # When we create a new image during scaling we loose the format
    # information, so remember it here.
    image_format=image.format

    current_size=image.size
    # Determine scale factor needed to get the right height
    if height is None:
        scale_height=None
    else:
        scale_height=(float(height)/float(current_size[1]))
    if width is None:
        scale_width=None
    else:
        scale_width=(float(width)/float(current_size[0]))

    if scale_height==scale_width or direction=="thumbnail":
        # The original already has the right aspect ratio, so we only need
        # to scale.
        image.thumbnail((width, height), PIL.Image.ANTIALIAS)
    else:
        if direction=="down":
            if scale_height is None or (scale_width is not None and scale_width>scale_height):
                # Width is the smallest dimension (relatively), so scale up
                # to the desired width
                new_width=width
                new_height=int(round(current_size[1]*scale_width))
            else:
                new_height=height
                new_width=int(round(current_size[0]*scale_height))
        else:
            if scale_height is None or (scale_width is not None and scale_width<scale_height):
                # Width is the largest dimension (relatively), so scale up
                # to the desired width
                new_width=width
                new_height=int(round(current_size[1]*scale_width))
            else:
                new_height=height
                new_width=int(round(current_size[0]*scale_height))

        image.draft(image.mode, (new_width, new_height))
        image=image.resize((new_width, new_height), PIL.Image.ANTIALIAS)

        if (width is not None and new_width>width) or (height is not None and new_height>height):
            if width is None:
                left=0
                right=new_width
            else:
                left=int((new_width-width)/2.0)
                right=left+width
            if height is None:
                height=new_height
            image=image.crop((left, 0, right, height))

    if image_format=="PNG":
        format="PNG"
    else:
        format="JPEG"

    if result is None:
        result=StringIO()
        image.save(result, format, quality=quality, optimize=True)
        result=result.getvalue()
    else:
        image.save(result, format, quality=quality, optimize=True)
        result.seek(0)

    return (result, format, image.size)
Example #8
0
def scaleImage(image, width=None, height=None, direction='down',
               quality=88, result=None):
    """Scale the given image data to another size and return the result
    as a string or optionally write in to the file-like `result` object.

    The `image` parameter can either be the raw image data (ie a `str`
    instance) or an open file.

    The `quality` parameter can be used to set the quality of the
    resulting image scales.

    The return value is a tuple with the new image, the image format and
    a size-tuple.  Optionally a file-like object can be given as the
    `result` parameter, in which the generated image scale will be stored.

    The `width`, `height`, `direction` parameters will be passed to
    :meth:`scalePILImage`, which performs the actual scaling.

    The generated image is a JPEG image, unless the original is a PNG or GIF
    image. This is needed to make sure alpha channel information is
    not lost, which JPEG does not support.
    """
    if isinstance(image, (bytes, str)):
        image = StringIO(image)
    image = PIL.Image.open(image)
    # When we create a new image during scaling we loose the format
    # information, so remember it here.
    format_ = image.format
    if format_ not in ('PNG', 'GIF'):
        # Always generate JPEG, except if format is PNG or GIF.
        format_ = 'JPEG'
    elif format_ == 'GIF':
        # GIF scaled looks better if we have 8-bit alpha and no palette
        format_ = 'PNG'

    icc_profile = image.info.get('icc_profile')
    image = scalePILImage(image, width, height, direction)

    # convert to simpler mode if possible
    colors = image.getcolors(maxcolors=256)
    if image.mode not in ('P', 'L') and colors:
        if format_ == 'JPEG':
            # check if it's all grey
            if all(rgb[0] == rgb[1] == rgb[2] for c, rgb in colors):
                image = image.convert('L')
        elif format_ == 'PNG':
            image = image.convert('P')

    if image.mode == 'RGBA' and format_ == 'JPEG':
        extrema = dict(zip(image.getbands(), image.getextrema()))
        if extrema.get('A') == (255, 255):
            # no alpha used, just change the mode, which causes the alpha band
            # to be dropped on save
            image.mode = "RGB"
        else:
            # switch to PNG, which supports alpha
            format_ = 'PNG'

    new_result = False

    if result is None:
        result = StringIO()
        new_result = True

    image.save(
        result,
        format_,
        quality=quality,
        optimize=True,
        progressive=True,
        icc_profile=icc_profile
    )

    if new_result:
        result = result.getvalue()
    else:
        result.seek(0)

    return result, format_, image.size
Example #9
0
def scaleImage(image,
               width=None,
               height=None,
               direction='down',
               quality=88,
               result=None):
    """Scale the given image data to another size and return the result
    as a string or optionally write in to the file-like `result` object.

    The `image` parameter can either be the raw image data (ie a `str`
    instance) or an open file.

    The `quality` parameter can be used to set the quality of the
    resulting image scales.

    The return value is a tuple with the new image, the image format and
    a size-tuple.  Optionally a file-like object can be given as the
    `result` parameter, in which the generated image scale will be stored.

    The `width`, `height`, `direction` parameters will be passed to
    :meth:`scalePILImage`, which performs the actual scaling.

    The generated image is a JPEG image, unless the original is a PNG or GIF
    image. This is needed to make sure alpha channel information is
    not lost, which JPEG does not support.
    """
    if isinstance(image, str):
        image = StringIO(image)
    image = PIL.Image.open(image)

    # When we create a new image during scaling we loose the format
    # information, so remember it here.
    format_ = image.format
    if format_ not in ('PNG', 'GIF'):
        # Always generate JPEG, except if format is PNG or GIF.
        format_ = 'JPEG'
    elif format_ == 'GIF':
        # GIF scaled looks better if we have 8-bit alpha and no palette
        format_ = 'PNG'

    image = scalePILImage(image, width, height, direction)

    # convert to simpler mode if possible
    if image.mode not in ('P', 'L') and image.getcolors(maxcolors=256):
        if format_ == 'JPEG':
            image = image.convert('L')
        elif format_ == 'PNG':
            image = image.convert('P')

    new_result = False

    if result is None:
        result = StringIO()
        new_result = True

    image.save(result,
               format_,
               quality=quality,
               optimize=True,
               progressive=True)

    if new_result:
        result = result.getvalue()
    else:
        result.seek(0)

    return result, format_, image.size
Example #10
0
def scaleImage(image, width=None, height=None, direction='down',
               quality=88, result=None):
    """Scale the given image data to another size and return the result
    as a string or optionally write in to the file-like `result` object.

    The `image` parameter can either be the raw image data (ie a `str`
    instance) or an open file.

    The `quality` parameter can be used to set the quality of the
    resulting image scales.

    The return value is a tuple with the new image, the image format and
    a size-tuple.  Optionally a file-like object can be given as the
    `result` parameter, in which the generated image scale will be stored.

    The `width`, `height`, `direction` parameters will be passed to
    :meth:`scalePILImage`, which performs the actual scaling.

    The generated image is a JPEG image, unless the original is a PNG or GIF
    image. This is needed to make sure alpha channel information is
    not lost, which JPEG does not support.
    """
    if isinstance(image, str):
        image = StringIO(image)
    image = PIL.Image.open(image)

    # When we create a new image during scaling we loose the format
    # information, so remember it here.
    format_ = image.format
    if format_ not in ('PNG', 'GIF'):
        # Always generate JPEG, except if format is PNG or GIF.
        format_ = 'JPEG'
    elif format_ == 'GIF':
        # GIF scaled looks better if we have 8-bit alpha and no palette
        format_ = 'PNG'

    image = scalePILImage(image, width, height, direction)

    # convert to simpler mode if possible
    if image.mode not in ('P', 'L') and image.getcolors(maxcolors=256):
        if format_ == 'JPEG':
            image = image.convert('L')
        elif format_ == 'PNG':
            image = image.convert('P')

    new_result = False

    if result is None:
        result = StringIO()
        new_result = True

    image.save(
        result,
        format_,
        quality=quality,
        optimize=True,
        progressive=True
    )

    if new_result:
        result = result.getvalue()
    else:
        result.seek(0)

    return result, format_, image.size
Example #11
0
def handle_image_from_xhr_upload(request, instance, attr_name):
    inicio = time_module.time()
    if attr_name in request.FILES:
        image_file = request.FILES[attr_name]
        img_name = image_file.name
    
    elif 'url' in request.POST: # If image comes from url
        url = request.POST['url']
        url = url.replace(" ", "%20")
        imgcontent = urllib.urlopen(url) # open the image contents
        image_file = StringIO(imgcontent.read()) # creates an in memory file object
        
        parsed_url = urlparse(url)
        img_name = parsed_url.path # gets the file name on url
    
    extension = img_name[img_name.rfind("."):] # gets the image extension
    
    # gets the ImageCrop attribute from the model
    image_crop_attr_obj = getattr(instance, attr_name) 
    
    upload_to = image_crop_attr_obj.field.upload_to
    time = int(datetime.now().microsecond)# current time to add on the file name
    
    # Open the uploaded (or downloaded in case it's from url) image
    image_file = Image.open(image_file)
    img_attr_obj = getattr(instance, attr_name)
    
    try:
        os.remove(img_attr_obj.path)
    except:
        pass
    
    try:
        last_original_path = img_attr_obj.path
        last_slash = last_original_path.rfind("/")
        
        if last_slash == -1:
            last_slash = last_original_path.rfind("\\")
        
        last_original_name = last_original_path[last_slash+1:]
        last_original_name = last_original_name.replace(attr_name, 
                                                        attr_name+"_original")
        
        os.remove(os.path.join(settings.MEDIA_ROOT, upload_to, last_original_name))
    except:
        pass
        
    ready_image_file = None
    ready_image_file = StringIO()
    image_file.save(ready_image_file , 'PNG', optimize = True)
    ready_image_file.seek(0)
    
    # Set the uploaded image to the file attribute of the imagefield
    img_attr_obj.file = ready_image_file
    
    # Seta o novo nome da imagem upada para o campo atual da iteracao (upload_to/nome.jpg)
    image_original_name = "%s%s_original_%s_%s%s" % (upload_to, attr_name, instance.id, time, extension)
    
    img_attr_obj.name = "%s%s_%s_%s%s" % (upload_to, attr_name, instance.id, time, extension)
    
    # Abre e salva a imagem atual no sistema de arquivos
    image_obj = Image.open( img_attr_obj )
    
    #image_obj.
    image_obj.save( img_attr_obj.path )
    
    # Dimensoes para usar como parametro na funcao adjust_img()
    dim = img_attr_obj.field.dimensions
    
    # Cria uma imagem cropavel ajustada para o tamanho especificado para o campo atual
    adjusted_image = adjust_img(img_attr_obj.path, dim[0], dim[1], dim[0], dim[1])
    adjusted_image.save( os.path.join(settings.MEDIA_ROOT,image_original_name))
    original_img_dim = adjusted_image.size
    
    box = getBox(adjusted_image, dim[0], dim[1])
    
    cropped_img = adjusted_image.crop(box)
    
    # Salva a imagem cropada no lugar da anterior (a imagem upada não tratada)
    cropped_img.save( img_attr_obj.path )
    cropped_img_dim = cropped_img.size
    
    instance.save()
    
    data = serializers.serialize("json", [instance])
    
    json_as_python = json.loads(data)
    
    original_dict_key = {
        attr_name+'_original': {
            'src':os.path.join("/media/", image_original_name),
            'dimensions':"%i,%i"%(original_img_dim[0], original_img_dim[1]),
        }
    }
    
    cropped_imgage = {
        attr_name+'_cropped': {
            'src': os.path.join("/media/", img_attr_obj.name),
            'dimensions':"%i,%i"%(cropped_img_dim[0], cropped_img_dim[1]),
        }
    }
    
    json_as_python[0].update(original_dict_key)
    json_as_python[0].update(cropped_imgage)
    
    data = json.dumps(json_as_python)
    return data