Apply modifiers to the images of a theme

        Modifies the images using the PIL.ImageEnhance module. Using
        this function, theme images are modified to given them a
        unique look and feel. Works best with PNG-based images.
480973
def _setup_images(directory, brightness, saturation, hue, preserve_transparency):
        
        for file_name in os.listdir(directory):
            with open(os.path.join(directory, file_name), "rb") as fi:
                image = Image.open(fi).convert("RGBA")
            # Only perform required operations
            if brightness != 1.0:
                enhancer = ImageEnhance.Brightness(image)
                image = enhancer.enhance(brightness)
            if saturation != 1.0:
                enhancer = ImageEnhance.Color(image)
                image = enhancer.enhance(saturation)
            if hue != 1.0:
                image = imgops.shift_hue(image, hue)
            if preserve_transparency is True:
                image = imgops.make_transparent(image)
            # Save the new image
            image.save(os.path.join(directory, file_name.replace("gif", "png")))
            image.close()
        for file_name in (item for item in os.listdir(directory) if item.endswith(".gif")):
            os.remove(os.path.join(directory, file_name))
594702
def set_image(self, img):
        ''''''
        self._bmp = wx.BitmapFromImage(img)
        self.SetMinSize((self._bmp.GetWidth(), self._bmp.GetHeight()))
577955
function apply(slides) {
      for (var i = 0, len = slides.length; i < len; i++) {
        var style = slides[i].style;
        var direction = Components.Direction.value;

        if (i !== 0) {
          style[MARGIN_TYPE[direction][0]] = this.value / 2 + 'px';
        } else {
          style[MARGIN_TYPE[direction][0]] = '';
        }

        if (i !== slides.length - 1) {
          style[MARGIN_TYPE[direction][1]] = this.value / 2 + 'px';
        } else {
          style[MARGIN_TYPE[direction][1]] = '';
        }
      }
    }
1097565
def apply(self, resource):
        
        if not isinstance(resource, Image.Image):
            raise ValueError('Unknown resource format')

        resource_format = resource.format
        if resource.mode != 'RGBA':  # pragma: no cover
            resource = resource.convert('RGBA')

        layer = Image.new('RGBA', resource.size, (0, 0, 0, 0))
        image, left, upper = getattr(self, '_' + self.position + '_position')(resource)
        layer.paste(image, (left, upper))

        image = Image.composite(layer, resource, layer)
        image.format = resource_format

        return image
1170587
def is_transparent(image):
    
    if not isinstance(image, Image.Image):
        # Can only deal with PIL images, fall back to the assumption that that
        # it's not transparent.
        return False
    return (image.mode in ('RGBA', 'LA') or
            (image.mode == 'P' and 'transparency' in image.info))
1166783
def set_image(self, **kwargs):
        
        self.image = {
            'url': kwargs.get('url'),
            'proxy_url': kwargs.get('proxy_url'),
            'height': kwargs.get('height'),
            'width': kwargs.get('width'),
        }
477443
def update_image(self):
        
        if self._image:
            self._image.set_cmap(self.get_cmap())
            _pylab.draw()
71609
public static <T extends ImageGray<T>>
	void applyTransform( T input , int transform[] , int minValue , T output ) {
		InputSanityCheck.checkSameShape(input, output);

		if( input instanceof GrayU8) {
			EnhanceImageOps.applyTransform((GrayU8) input, transform, (GrayU8) output);
		} else if( input instanceof GrayS8) {
			EnhanceImageOps.applyTransform((GrayS8)input,transform,minValue,(GrayS8)output);
		} else if( input instanceof GrayU16) {
			EnhanceImageOps.applyTransform((GrayU16)input,transform,(GrayU16)output);
		} else if( input instanceof GrayS16) {
			EnhanceImageOps.applyTransform((GrayS16)input,transform,minValue,(GrayS16)output);
		} else if( input instanceof GrayS32) {
			EnhanceImageOps.applyTransform((GrayS32)input,transform,minValue,(GrayS32)output);
		} else {
			throw new IllegalArgumentException("Image type not supported. "+input.getClass().getSimpleName());
		}
	}
1146203
private void applyTheme() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setSeekBarColor(ThemeUtil.getColor(getContext(), R.attr.colorAccent));
        }
    }
783012
def convertImagesToPIL(self, images, dither, nq=0):
        

        # Convert to PIL images
        images2 = []
        for im in images:
            if isinstance(im, Image.Image):
                images2.append(im)
            elif np and isinstance(im, np.ndarray):
                if im.ndim == 3 and im.shape[2] == 3:
                    im = Image.fromarray(im, 'RGB')
                elif im.ndim == 3 and im.shape[2] == 4:
                    im = Image.fromarray(im[:, :, :3], 'RGB')
                elif im.ndim == 2:
                    im = Image.fromarray(im, 'L')
                images2.append(im)

        # Convert to paletted PIL images
        images, images2 = images2, []

        # Adaptive PIL algorithm
        AD = Image.ADAPTIVE
        for im in images:
            im = im.convert('P', palette=AD, dither=dither)
            images2.append(im)

        # Done
        return images2
738502
protected function applyRules()
    {
        // Check if there are rules for this field
        $rules_key = 'images.' . ($this->name ?: 'default');
        if (!$rules = Former::getRules($rules_key)) {
            return;
        }

        // If there already is an image, drop the forced requirement
        if ($this->hasImage() && array_key_exists('required', $rules)) {
            unset($rules['required']);
            $this->addClass('required'); // So the icon shows up
        }

        // Apply rules using Former's LiveValidation
        $live = new LiveValidation($this);
        $live->apply($rules);
    }
1224561
def process_image(self, decorator):
        
        savefig_dir = self.savefig_dir
        source_dir = self.source_dir
        saveargs = decorator.split(' ')
        filename = saveargs[1]
        # insert relative path to image file in source
        outfile = os.path.relpath(os.path.join(savefig_dir,filename),
                    source_dir)

        imagerows = ['.. image:: %s'%outfile]

        for kwarg in saveargs[2:]:
            arg, val = kwarg.split('=')
            arg = arg.strip()
            val = val.strip()
            imagerows.append('   :%s: %s'%(arg, val))

        image_file = os.path.basename(outfile) # only return file name
        image_directive = '\n'.join(imagerows)
        return image_file, image_directive
300338
function adapt(callback) {
      /*
       * For Graphics Magick docs: http://www.graphicsmagick.org/GraphicsMagick.html#details-geometry
       * Inspiration: http://stackoverflow.com/questions/14705152/thumbnails-from-graphics-magick-without-upscaling
       */

      co(function*() {
        let externalStream = config.stream(path);

        if (!externalStream) {
          // Ensure the file exists on the filesystem.
          try {
            yield Q.nfcall(fs.stat, mkpath(imagesDir, matches.path));
          } catch (e) {
            return next();
          }
        }

        // Stream the image into a buffer. (passing a stream directly into GM was causing problems with gcloud streams)
        let stream = externalStream || fs.createReadStream(mkpath(imagesDir, path));

        try {
          var buffer = yield Q.nfcall(stream2buffer, stream);
        } catch (e) {
          return callback(e);
        }

        let img = gm(buffer);
        
        // Set up some options
        img
          // .filter('Triangle')
          // Not sure if these work in GM, but they are IM options
          // .define('filter:support=2')
          // .define('jpeg:fancy-upsampling=off')
          // .unsharp(0.25, 0.25, 8, 0.065)
          // .colors(136)
          // .dither(false)
          // .colorspace('sRGB')
          .out('-background', bg || (mimetype == 'image/png' ? 'transparent' : 'white'));

        img.size(function(err, nativeSize) {
          if (err || typeof nativeSize == 'undefined' || typeof nativeSize.width == 'undefined' || typeof nativeSize.height == 'undefined') {
            return callback(err || 'Failed to retrieve image dimensions.');
          }

          /**
           * Validate dimensions & determine sizing rules.
           */
          let imageWidth = width, imageHeight = height;       // The size of the image itself
          let canvasWidth = width, canvasHeight = height;     // The size of the canvas around the image
          let allowResize;

          // If we're resizing, ensure we never exceed the native image dimensions.
          if (!imageWidth && !imageHeight) {
            // Using native image size, no resizing necessary.
            imageWidth = nativeSize.width;
            imageHeight = nativeSize.height;
            canvasWidth = nativeSize.width;
            canvasHeight = nativeSize.height;

            allowResize = false;
          } else if ((imageWidth && !imageHeight) || (!imageWidth && imageHeight)) {
            // One size provided, scale the other proportionally.
            if (imageWidth) {
              imageHeight = Math.round(imageWidth * (nativeSize.height / nativeSize.width));
              canvasHeight = imageHeight >= nativeSize.height ? nativeSize.height : imageHeight;  // trim extra space from canvas height
            } else {
              imageWidth = Math.round(imageHeight * (nativeSize.width / nativeSize.height));
              canvasWidth = imageWidth >= nativeSize.width ? nativeSize.width : imageWidth;       // trim extra space from canvas width
            }

            allowResize = imageWidth < nativeSize.width && imageHeight < nativeSize.height;
          } else {
            // Two sizes provided.
            if (imageWidth > nativeSize.width && imageHeight > nativeSize.height) {
              // Do not exceed the native image size.
              imageWidth = nativeSize.width;
              imageHeight = nativeSize.height;
              allowResize = false;
            } else {
              if (imageWidth > nativeSize.width) {
                // Preserve requested height, but correct the width.
                imageWidth = 0;   // auto
              } else if (imageHeight > nativeSize.height) {
                // Preserve requested width, but correct the height.
                imageHeight = 0;  // auto
              }

              // Sizes are fine, fit into the requested box.
              allowResize = true;
            }
          }

          /**
           * Adapt the image.
           */
          
          if (mode == MODE_ASPECT_FILL) {
            img
              .resize(width, height, '^')
              .gravity('Center')
              .crop(width, height);
          } else if (mode == MODE_ASPECT_FIT) {
            if (allowResize) {
              let w = imageWidth == 0 ? null : (crop ? `${width}^` : imageWidth);
              let h = imageHeight == 0 ? null : (crop ? `${height}^` : imageHeight);

              img = img.resize(w, h);
            }

            img
              .gravity('Center')
              .extent(canvasWidth, canvasHeight);
          }

          img
            .quality(config.default.quality)
            .strip()
            .stream(function(err, stdout, stderr) {
              if (err) {
                return callback(err);
              }

              // calling .trim() on a GM object seems to have no effect,
              // so we need to perform that on the buffer if necessary.
              if (!trim) {
                return callback(null, stdout);
              }

              gm(stdout).trim().stream(function(err, stdout, stderr) {
                if (err) {
                  return callback(err);
                }

                callback(null, stdout);
              });
            });

        }); // /size
      }); // /co
    }
664041
public function apply(Picture $picture)
    {
        $resource = $picture->getResource();

        if($picture->isGd())
        {
            imagefilter($resource, IMG_FILTER_GRAYSCALE);

            $picture->setResource($resource);
        }
        else
        {
            $resource->modulateImage(100, 0, 100);
        }
    }
103551
public void update (Image image) {
    // if we're a repeating texture (or we want mipmaps) and this image is non-POT on the relevant
    // axes, we need to scale it before we upload it; we'll just do this on the CPU since it feels
    // like creating a second texture, a frame buffer to render into it, sending a GPU batch and
    // doing all the blah blah blah is going to be more expensive overall
    if (config.repeatX || config.repeatY || config.mipmaps) {
      int pixWidth = image.pixelWidth(), pixHeight = image.pixelHeight();
      int potWidth = config.toTexWidth(pixWidth), potHeight = config.toTexWidth(pixHeight);
      if (potWidth != pixWidth || potHeight != pixHeight) {
        Canvas scaled = gfx.createCanvasImpl(Scale.ONE, potWidth, potHeight);
        scaled.draw(image, 0, 0, potWidth, potHeight);
        scaled.image.upload(gfx, this);
        scaled.close();
      } else image.upload(gfx, this); // fast path, woo!
    }
    else image.upload(gfx, this); // fast path, woo!
    if (config.mipmaps) gfx.gl.glGenerateMipmap(GL_TEXTURE_2D);
  }
1281372
def gen_colors(img):
    """"""
    magick_command = has_im()

    for i in range(0, 20, 1):
        raw_colors = imagemagick(16 + i, img, magick_command)

        if len(raw_colors) > 16:
            break

        elif i == 19:
            logging.error("Imagemagick couldn't generate a suitable palette.")
            sys.exit(1)

        else:
            logging.warning("Imagemagick couldn't generate a palette.")
            logging.warning("Trying a larger palette size %s", 16 + i)

    return [re.search("#.{6}", str(col)).group(0) for col in raw_colors[1:]]
1127790
function applyTheme(theme) {
        Object.keys(theme).forEach(function(prop) {
            if (prototypeBlacklist.indexOf(prop) >= 0) {
                return;
            }
            if (typeof theme[prop] == 'string') {
                // Multiple colours white-space seperated #45, e.g. "red bold", #18
                theme[prop] = theme[prop].split(' ');
            }
            addProperty(prop, function () {
                var ret = this;
                for (var t=0; t<theme[prop].length; t++) {
                    ret = colour[theme[prop][t]](ret);
                }
                return ret;
            });
        });
    }