this method allow us to specify a quality for our image
 e.g. <process quality: 60>
777358
def quality(percentage)
      manipulate! do |img|
        img.quality(percentage.to_s)
        img = yield(img) if block_given?
        img
      end
    end
647952
protected RenderedImage doFilter(BufferedImage pImage, ServletRequest pRequest, ImageServletResponse pResponse) {

        // Get quality setting
        // SMOOTH | FAST | REPLICATE | DEFAULT | AREA_AVERAGING
        // See Image (mHints)
        int quality = getQuality(pRequest.getParameter(PARAM_SCALE_QUALITY));

        // Get units, default is pixels
        // PIXELS | PERCENT | METRIC | INCHES
        int units = getUnits(pRequest.getParameter(PARAM_SCALE_UNITS));
        if (units == UNITS_UNKNOWN) {
            log("Unknown units for scale, returning original.");
            return pImage;
        }

        // Use uniform scaling? Default is true
        boolean uniformScale = ServletUtil.getBooleanParameter(pRequest, PARAM_SCALE_UNIFORM, true);

        // Get dimensions
        int width = ServletUtil.getIntParameter(pRequest, PARAM_SCALE_X, -1);
        int height = ServletUtil.getIntParameter(pRequest, PARAM_SCALE_Y, -1);

        // Get dimensions for scaled image
        Dimension dim = getDimensions(pImage, width, height, units, uniformScale);

        width = (int) dim.getWidth();
        height = (int) dim.getHeight();

        // Return scaled instance directly
        return ImageUtil.createScaled(pImage, width, height, quality);
    }
1353996
public static void optimizeGraphicsQuality(Graphics2D g)
    {
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    }
699076
def generate_thumbnail(self, thumbnail_options, high_resolution=False,
                           silent_template_exception=False):
        
        thumbnail_options = self.get_options(thumbnail_options)
        orig_size = thumbnail_options['size']  # remember original size
        # Size sanity check.
        min_dim, max_dim = 0, 0
        for dim in orig_size:
            try:
                dim = int(dim)
            except (TypeError, ValueError):
                continue
            min_dim, max_dim = min(min_dim, dim), max(max_dim, dim)
        if max_dim == 0 or min_dim < 0:
            raise exceptions.EasyThumbnailsError(
                "The source image is an invalid size (%sx%s)" % orig_size)

        if high_resolution:
            thumbnail_options['size'] = (orig_size[0] * 2, orig_size[1] * 2)
        image = engine.generate_source_image(
            self, thumbnail_options, self.source_generators,
            fail_silently=silent_template_exception)
        if image is None:
            raise exceptions.InvalidImageFormatError(
                "The source file does not appear to be an image")

        thumbnail_image = engine.process_image(image, thumbnail_options,
                                               self.thumbnail_processors)
        if high_resolution:
            thumbnail_options['size'] = orig_size  # restore original size

        filename = self.get_thumbnail_name(
            thumbnail_options,
            transparent=utils.is_transparent(thumbnail_image),
            high_resolution=high_resolution)
        quality = thumbnail_options['quality']
        subsampling = thumbnail_options['subsampling']

        img = engine.save_image(
            thumbnail_image, filename=filename, quality=quality,
            subsampling=subsampling)
        data = img.read()

        thumbnail = ThumbnailFile(
            filename, file=ContentFile(data), storage=self.thumbnail_storage,
            thumbnail_options=thumbnail_options)
        thumbnail.image = thumbnail_image
        thumbnail._committed = False

        return thumbnail
586880
def encoded_image(image, options = {})
      target_format = options[:format] || default_render_format

      unless target_format.in?(Alchemy::Picture.allowed_filetypes)
        raise WrongImageFormatError.new(self, target_format)
      end

      options = {
        flatten: target_format != 'gif' && image_file_format == 'gif'
      }.merge(options)

      encoding_options = []

      if target_format =~ /jpe?g/
        quality = options[:quality] || Config.get(:output_image_jpg_quality)
        encoding_options << "-quality #{quality}"
      end

      if options[:flatten]
        encoding_options << '-flatten'
      end

      convertion_needed = target_format != image_file_format || encoding_options.present?

      if has_convertible_format? && convertion_needed
        image = image.encode(target_format, encoding_options.join(' '))
      end

      image
    end
1020877
private void scaleToOutputResolution(Image image) {

        float factor = m_sharedContext.getDotsPerPixel();
        if (factor != 1.0f) {
            image.scaleAbsolute(image.getPlainWidth() * factor, image.getPlainHeight() * factor);
        }
    }
1088730
def optimize(image, fmt='jpeg', quality=80):
    
    from io import BytesIO

    if IMAGE_OPTIMIZATION_CMD and is_tool(IMAGE_OPTIMIZATION_CMD):
        image_buffer = BytesIO()
        image.save(image_buffer, format=fmt, quality=quality)
        image_buffer.seek(0)  # If you don't reset the file pointer, the read command returns an empty string
        p1 = subprocess.Popen(IMAGE_OPTIMIZATION_CMD, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        output_optim, output_err = p1.communicate(image_buffer.read())
        if not output_optim:
            logger.debug("No image buffer received from IMAGE_OPTIMIZATION_CMD")
            logger.debug("output_err: {0}".format(output_err))
            return image
        im = Image.open(BytesIO(output_optim))
        return im
    else:
        return image
1143578
def iiif_image_api(request, identifier_param, region_param, size_param,
                   rotation_param, quality_param, format_param):
    
    ik_image, image = _get_image_or_404(identifier_param, load_image=True)

    is_transparent = et_utils.is_transparent(image)
    is_grayscale = image.mode in ('L', 'LA')

    # Map format names used for IIIF URL path extension to proper name
    format_mapping = {
        'jpg': 'jpeg',
        'tif': 'tiff',
    }

    try:
        # Parse region
        x, y, r_width, r_height = parse_region(
            region_param, image.width, image.height)

        # Parse size
        s_width, s_height = parse_size(size_param, r_width, r_height)

        # Parse rotation
        is_mirrored, rotation_degrees = \
            parse_rotation(rotation_param, s_width, s_height)

        # Parse quality
        quality = parse_quality(quality_param)

        # Parse format
        # TODO Add support for unsupported formats (see `parse_format`)
        image_format = os.path.splitext(ik_image.image.name)[1][1:].lower()
        output_format = parse_format(format_param, image_format)
        corrected_format = format_mapping.get(output_format, output_format)

        # Redirect to canonical URL if appropriate, per
        # http://iiif.io/api/image/2.1/#canonical-uri-syntax
        canonical_path = make_canonical_path(
            identifier_param, image.width, image.height,
            (x, y, r_width, r_height),  # Region
            (s_width, s_height),  # Size
            (is_mirrored, rotation_degrees),  # Rotation
            quality,
            output_format
        )
        if request.path != canonical_path:
            return HttpResponseRedirect(canonical_path)

        # Determine storage file name for item
        if iiif_storage:
            storage_path = build_iiif_file_storage_path(
                canonical_path, ik_image, iiif_storage)
        else:
            storage_path = None

        # Load pre-generated image from storage if one exists and is up-to-date
        # with the original image (per timestampt info embedded in the storage
        # path)
        # TODO The exists lookup is slow for S3 storage, cache metadata?
        # TODO Detect when original image would be unchanged & use it directly?
        if (
            storage_path and
            iiif_storage.exists(storage_path)
        ):
            if is_remote_storage(iiif_storage, storage_path):
                return HttpResponseRedirect(iiif_storage.url(storage_path))
            else:
                return FileResponse(
                    iiif_storage.open(storage_path),
                    content_type='image/%s' % corrected_format,
                )

        ##################
        # Generate image #
        ##################

        # Apply region
        if x or y or r_width != image.width or r_height != image.height:
            box = (x, y, x + r_width, y + r_height)
            image = image.crop(box)

        # Apply size
        if s_width != r_width or s_height != r_height:
            size = (s_width, s_height)
            image = image.resize(size)

        # TODO Apply rotation

        # Apply quality
        # Much of this is cribbed from easythumbnails' `colorspace` processor
        # TODO Replace with glamkit-imagetools' sRGB colour space converter?
        if quality in ('default', 'color') and not is_grayscale:
            if is_transparent:
                new_mode = 'RGBA'
            else:
                new_mode = 'RGB'
        elif is_grayscale or quality == 'gray':
            if is_transparent:
                new_mode = 'LA'
            else:
                new_mode = 'L'
        if new_mode != image.mode:
            image = image.convert(new_mode)

        # Apply format and "save"
        result_image = BytesIO()
        image.save(result_image, format=corrected_format)

        # Save generated image to storage if possible
        if storage_path:
            iiif_storage.save(storage_path, result_image)

        if iiif_storage and is_remote_storage(iiif_storage, storage_path):
            return HttpResponseRedirect(iiif_storage.url(storage_path))
        else:
            result_image.seek(0)  # Reset image file in case it's just created
            return FileResponse(
                result_image.read(),
                content_type='image/%s' % corrected_format,
            )
    # Handle error conditions per iiif.io/api/image/2.1/#server-responses
    except ClientError, ex:
        return HttpResponseBadRequest(ex.message)  # 400 response
    except UnsupportedError, ex:
        return HttpResponseNotImplemented(ex.message)
737381
def img_opacity(image, opacity):
    
    # Validate parameters
    assert 0 <= opacity <= 1, 'Opacity must be a float between 0 and 1'
    assert os.path.isfile(image), 'Image is not a file'

    # Open image in RGBA mode if not already in RGBA
    im = Image.open(image)
    if im.mode != 'RGBA':
        im = im.convert('RGBA')
    else:
        im = im.copy()

    # Adjust opacity
    alpha = im.split()[3]
    alpha = ImageEnhance.Brightness(alpha).enhance(opacity)
    im.putalpha(alpha)

    # Save modified image file
    dst = _add_suffix(image, str(str(int(opacity * 100)) + '%'), ext='.png')
    im.save(dst)
    return dst
26153
def image_format(value):
    

    if value.image.format.upper() not in constants.ALLOWED_IMAGE_FORMATS:
        raise ValidationError(MESSAGE_INVALID_IMAGE_FORMAT)
1205442
public void process( T image , GrayF32 intensity ) {
		int maxFeatures = (int)(maxFeaturesFraction*image.width*image.height);
		candidatesLow.reset();
		candidatesHigh.reset();
		this.image = image;

		if( stride != image.stride ) {
			stride = image.stride;
			offsets = DiscretizedCircle.imageOffsets(radius, image.stride);
		}
		helper.setImage(image,offsets);

		for (int y = radius; y < image.height-radius; y++) {
			int indexIntensity = intensity.startIndex + y*intensity.stride + radius;
			int index = image.startIndex + y*image.stride + radius;
			for (int x = radius; x < image.width-radius; x++, index++,indexIntensity++) {

				int result = helper.checkPixel(index);

				if( result < 0 ) {
					intensity.data[indexIntensity] = helper.scoreLower(index);
					candidatesLow.add(x,y);
				} else if( result > 0) {
					intensity.data[indexIntensity] = helper.scoreUpper(index);
					candidatesHigh.add(x,y);
				} else {
					intensity.data[indexIntensity] = 0;
				}
			}
			// check on a per row basis to reduce impact on performance
			if( candidatesLow.size + candidatesHigh.size >= maxFeatures )
				break;
		}
	}
69290
def image_postprocess(imagefile, output, size, crop, render):
    
    try:
        from PIL import Image
    except ImportError:
        import Image

    img = Image.open(imagefile)
    size_crop = None
    img_resized = img
    if size and crop and crop.lower() == 'true':
        width_raw, height_raw = img.size
        width, height = size
        height_better = int(height_raw * (float(width) / width_raw))
        if height < height_better:
            size_crop = (0, 0, width, height)

    try:
        if size_crop:
            size_better = width, height_better
            img_better = img.resize(size_better, Image.ANTIALIAS)
            img_resized = img_better.crop(size_crop)
        elif size:
            img_resized = img.resize(size, Image.ANTIALIAS)

        # If save with 'bmp' use default mode('RGBA'), it will raise:
        # "IOError: cannot write mode RGBA as BMP".
        # So, we need convert image mode
        # from 'RGBA' to 'RGB' for 'bmp' format.
        if render == 'bmp':
            img_resized = img_resized.convert('RGB')
        # Fix IOError: cannot write mode RGBA as XBM
        elif render == 'xbm':
            img_resized = img_resized.convert('1')
        # Works with either filename or file-like object
        img_resized.save(output, render)
    except KeyError:
        raise UnsupportedImageFormat
    except IOError as e:
        raise CaptureError(e)
222910
def set_quality_index(self):
        """"""
        window_start = self.parent.value('window_start')
        window_length = self.parent.value('window_length')
        qual = self.annot.get_stage_for_epoch(window_start, window_length,
                                              attr='quality')
        #lg.info('winstart: ' + str(window_start) + ', quality: ' + str(qual))

        if qual is None:
            self.idx_quality.setCurrentIndex(-1)
        else:
            self.idx_quality.setCurrentIndex(QUALIFIERS.index(qual))
661552
private static function setQuality(int $quality = 90): void
    {
        $quality = $quality < 10 || $quality > 100 ? 90 : $quality;
        static::$quality = $quality;
        static::$qualityPNG = (int)\round((100 - $quality) / 10, 0);
    }
1261694
public function getDefaultJpegQuality()
    {
        $result = $this->config->get('concrete.misc.default_jpeg_image_compression');
        if ($this->valn->integer($result, 0, 100)) {
            $result = (int) $result;
        } else {
            $result = static::DEFAULT_JPEG_QUALITY;
        }

        return $result;
    }
879975
public void setImage(T image) {
		blur.reshape(image.width,image.height);
		filterBlur.process(image,blur);
		describe.setImage(image);
	}
131111
@Nonnull
  public FineUploader5Validation setImageMinWidth (@Nonnegative final int nImageMinWidth)
  {
    ValueEnforcer.isGE0 (nImageMinWidth, "ImageMinWidth");
    m_nValidationImageMinWidth = nImageMinWidth;
    return this;
  }