Converts the given image into a format for quick upload to the GPU.
968248
static BufferedImage convertImage (BufferedImage image) {
    switch (image.getType()) {
    case BufferedImage.TYPE_INT_ARGB_PRE:
      return image; // Already good to go
    case BufferedImage.TYPE_4BYTE_ABGR:
      image.coerceData(true); // Just premultiply the alpha and it's fine
      return image;
    }

    // Didn't know an easy thing to do, so create a whole new image in our preferred format
    BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(),
                                                     BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics g = convertedImage.getGraphics();
    g.setColor(new Color(0f, 0f, 0f, 0f));
    g.fillRect(0, 0, image.getWidth(), image.getHeight());
    g.drawImage(image, 0, 0, null);

    return convertedImage;
  }
479012
def latex_to_img(tex):
        """"""
        with tempfile.TemporaryDirectory() as tmpdirname:
            with open(tmpdirname + r'\tex.tex', 'w') as f:
                f.write(tex)

            os.system(r"latex {0}\tex.tex -halt-on-error -interaction=batchmode -disable-installer -aux-directory={0} "
                      r"-output-directory={0}".format(tmpdirname))
            os.system(r"dvipng -T tight -z 9 --truecolor -o {0}\tex.png {0}\tex.dvi".format(tmpdirname))
            # os.system(r'latex2png ' + tmpdirname)

            image = pygame.image.load(tmpdirname + r'\tex.png')

        return image
131045
def _gdcm_to_numpy(self, image):
        
        gdcm_typemap = {
            gdcm.PixelFormat.INT8:     numpy.int8,
            gdcm.PixelFormat.UINT8:    numpy.uint8,
            gdcm.PixelFormat.UINT16:   numpy.uint16,
            gdcm.PixelFormat.INT16:    numpy.int16,
            gdcm.PixelFormat.UINT32:   numpy.uint32,
            gdcm.PixelFormat.INT32:    numpy.int32,
            gdcm.PixelFormat.FLOAT32:  numpy.float32,
            gdcm.PixelFormat.FLOAT64:  numpy.float64
        }
        pixel_format = image.GetPixelFormat().GetScalarType()
        if pixel_format in gdcm_typemap:
            self.data_type = gdcm_typemap[pixel_format]
        else:
            raise KeyError(''.join(pixel_format, \
                " is not a supported pixel format"))

        #dimension = image.GetDimension(0), image.GetDimension(1)
        self.dimensions = image.GetDimension(1), image.GetDimension(0)
        gdcm_array = image.GetBuffer()

        # GDCM returns char* as type str. This converts it to type bytes
        if sys.version_info >= (3, 0):
            gdcm_array = gdcm_array.encode(sys.getfilesystemencoding(), "surrogateescape")

        # use float for accurate scaling
        dimensions = image.GetDimensions()
        result = numpy.frombuffer(gdcm_array, dtype=self.data_type).astype(float)
        if len(dimensions) == 3:
            # for cine (animations) there are 3 dims: x, y, number of frames
            result.shape = dimensions[2], dimensions[0], dimensions[1]
        else:
            result.shape = dimensions
        return result
266323
def to_gpu(*args):
    
    if len(args) > 1:
        return (cp.asarray(x) for x in args)
    else:
        return cp.asarray(args[0])
293983
def numpy_to_texture(image):
    """"""
    if not isinstance(image, np.ndarray):
        raise TypeError('Unknown input type ({})'.format(type(image)))
    if image.ndim != 3 or image.shape[2] != 3:
        raise AssertionError('Input image must be nn by nm by RGB')
    grid = vtki.UniformGrid((image.shape[1], image.shape[0], 1))
    grid.point_arrays['Image'] = np.flip(image.swapaxes(0,1), axis=1).reshape((-1, 3), order='F')
    grid.set_active_scalar('Image')
    return image_to_texture(grid)
1007271
def _convert(self, image, output=None):
        """"""
        with Image.open(image) as im:
            width, height = im.size

            co = CanvasObjects()
            co.add(CanvasImg(image, 1.0, w=width, h=height))

            return WatermarkDraw(co, tempdir=self.tempdir, pagesize=(width, height)).write(output)
1135754
def _convert_image(self, im):
        
        pixels   = []
        pix_line = ""
        im_left  = ""
        im_right = ""
        switch   = 0
        img_size = [ 0, 0 ]


        if im.size[0] > 512:
            print  "WARNING: Image is wider than 512 and could be truncated at print time "
        if im.size[1] > 255:
            raise ImageSizeError()

        im_border = self._check_image_size(im.size[0])
        for i in range(im_border[0]):
            im_left += "0"
        for i in range(im_border[1]):
            im_right += "0"

        for y in range(im.size[1]):
            img_size[1] += 1
            pix_line += im_left
            img_size[0] += im_border[0]
            for x in range(im.size[0]):
                img_size[0] += 1
                RGB = im.getpixel((x, y))
                im_color = (RGB[0] + RGB[1] + RGB[2])
                im_pattern = "1X0"
                pattern_len = len(im_pattern)
                switch = (switch - 1 ) * (-1)
                for x in range(pattern_len):
                    if im_color <= (255 * 3 / pattern_len * (x+1)):
                        if im_pattern[x] == "X":
                            pix_line += "%d" % switch
                        else:
                            pix_line += im_pattern[x]
                        break
                    elif im_color > (255 * 3 / pattern_len * pattern_len) and im_color <= (255 * 3):
                        pix_line += im_pattern[-1]
                        break 
            pix_line += im_right
            img_size[0] += im_border[1]

        return (pix_line, img_size)
1280940
private static void adjustQualityFromImage(Map<String, Float> pFormatQuality, BufferedImage pImage) {
        // NOTE: The values are all made-up. May need tuning.

        // If pImage.getColorModel() instanceof IndexColorModel
        //    JPEG qs*=0.6
        //    If NOT binary or 2 color index
        //        WBMP qs*=0.5
        // Else
        //    GIF qs*=0.02
        //    PNG qs*=0.9 // JPEG is smaller/faster
        if (pImage.getColorModel() instanceof IndexColorModel) {
            adjustQuality(pFormatQuality, FORMAT_JPEG, 0.6f);

            if (pImage.getType() != BufferedImage.TYPE_BYTE_BINARY ||  ((IndexColorModel) pImage.getColorModel()).getMapSize() != 2) {
                adjustQuality(pFormatQuality, FORMAT_WBMP, 0.5f);
            }
        }
        else {
            adjustQuality(pFormatQuality, FORMAT_GIF, 0.01f);
            adjustQuality(pFormatQuality, FORMAT_PNG, 0.99f); // JPEG is smaller/faster
        }

        // If pImage.getColorModel().hasTransparentPixels()
        //    JPEG qs*=0.05
        //    WBMP qs*=0.05
        //    If NOT transparency == BITMASK
        //        GIF qs*=0.8
        if (ImageUtil.hasTransparentPixels(pImage, true)) {
            adjustQuality(pFormatQuality, FORMAT_JPEG, 0.009f);
            adjustQuality(pFormatQuality, FORMAT_WBMP, 0.009f);

            if (pImage.getColorModel().getTransparency() != Transparency.BITMASK) {
                adjustQuality(pFormatQuality, FORMAT_GIF, 0.8f);
            }
        }
    }
584979
def processed_image(image, options = {})
      size = options[:size]
      upsample = !!options[:upsample]

      return image unless size.present? && has_convertible_format?

      if options[:crop]
        crop(size, options[:crop_from], options[:crop_size], upsample)
      else
        resize(size, upsample)
      end
    end
864153
private BufferedImage to8Bit1ComponentGrayScale(int[][] decoded, int width, int height) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        byte[] imageBuffer = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();

        for (int i = 0; i < imageBuffer.length; i++) {
            imageBuffer[i] = (byte) decoded[0][i];
        }

        return image;
    }
538077
def write_image_to_disk(self, msg, result, fh):
        """"""
        fh.write(base64.b64decode(result.group(1).encode('utf-8')))
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);
  }
1238510
def to_image(options = {})
      options = {
          tileable: false,
      }.merge! options

      # Create a new Image from the flipped pixel data.
      stub = ImageStub.new to_blob, width, height
      if defined? TexPlay
        Gosu::Image.new $window, stub, options[:tileable], options
      else
        Gosu::Image.new $window, stub, options[:tileable]
      end
    end
302090
def to_imgur_format(params):
    """"""
    if params is None:
        return None
    return dict((k, convert_general(val)) for (k, val) in params.items())
1328373
def upscale(image, ratio):
    
    if not isinstance(image, np.ndarray):
        raise ValueError('Expected ndarray')
    if ratio < 1:
        raise ValueError('Ratio must be greater than 1 (ratio=%f)' % ratio)
    width = int(math.floor(image.shape[1] * ratio))
    height = int(math.floor(image.shape[0] * ratio))
    channels = image.shape[2]
    out = np.ndarray((height, width, channels), dtype=np.uint8)
    for x, y in np.ndindex((width, height)):
        out[y, x] = image[int(math.floor(y / ratio)), int(math.floor(x / ratio))]
    return out
542014
def convert_images_to_pil(self, images, dither, nq=0, images_info=None):
        

        # 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')
                    self.transparency = True
                    im = Image.fromarray(im[:, :, :4], 'RGBA')
                elif im.ndim == 2:
                    im = Image.fromarray(im, 'L')
                images2.append(im)

        # Convert to paletted PIL images
        images, images2 = images2, []
        if nq >= 1:
            # NeuQuant algorithm
            for im in images:
                im = im.convert("RGBA")  # NQ assumes RGBA
                nq_instance = NeuQuant(im, int(nq))  # Learn colors from image
                if dither:
                    im = im.convert("RGB").quantize(palette=nq_instance.palette_image(), colors=255)
                else:
                    im = nq_instance.quantize(im, colors=255)  # Use to quantize the image itself

                self.transparency = True  # since NQ assumes transparency
                if self.transparency:
                    alpha = im.split()[3]
                    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
                    im.paste(255, mask=mask)
                images2.append(im)
        else:
            # for index,im in enumerate(images):
            for i in range(len(images)):
                im = images[i].convert('RGB').convert('P', palette=Image.ADAPTIVE, dither=dither, colors=255)
                if self.transparency:
                    alpha = images[i].split()[3]
                    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
                    im.paste(255, mask=mask)
                images2.append(im)

        # Done
        return images2
418610
def wrap(self, image):
        
        if hasattr(image, 'size') and hasattr(image, 'convert'):
            # Treat image as PIL/pillow Image object
            self.width, self.height = image.size
            array_type = ctypes.c_ubyte * 4 * (self.width * self.height)
            self.pixels_array = array_type()
            pixels = image.convert('RGBA').getdata()
            for i, pixel in enumerate(pixels):
                self.pixels_array[i] = pixel
        else:
            self.width, self.height, pixels = image
            array_type = ctypes.c_ubyte * 4 * self.width * self.height
            self.pixels_array = array_type()
            for i in range(self.height):
                for j in range(self.width):
                    for k in range(4):
                        self.pixels_array[i][j][k] = pixels[i][j][k]
        pointer_type = ctypes.POINTER(ctypes.c_ubyte)
        self.pixels = ctypes.cast(self.pixels_array, pointer_type)