Convert a single line of text *m* to a raster image,
    by rendering it using the font in *font*.

    A triple of (*width*, *height*, *pixels*) is returned;
    *pixels* is in boxed row packed pixel format.
6913
def linetoraster(m):
    

    # Assumes monospaced font.
    x = 8 * len(m)
    y = 8
    return x, y, [itertools.chain(*row) for row in zip(*map(char, m))]
430165
public short[] getPixelValues(WritableRaster raster) {
		DataBufferUShort buffer = (DataBufferUShort) raster.getDataBuffer();
		short[] pixelValues = buffer.getData();
		return pixelValues;
	}
671376
def text2art(text, font=DEFAULT_FONT, chr_ignore=True):
    
    """
    letters = standard_dic
    text_temp = text
    if isinstance(text, str) is False:
        raise artError(TEXT_TYPE_ERROR)
    if isinstance(font, str) is False:
        raise artError(FONT_TYPE_ERROR)
    font = font.lower()
    fonts = sorted(FONT_MAP.keys())
    font = indirect_font(font, fonts, text)
    letters = FONT_MAP[font][0]
    if FONT_MAP[font][1]:
        text_temp = text.lower()
    if font in UPPERCASE_FONTS:
        text_temp = text.upper()
    word_list = text_temp.split("\n")
    result = ""
    for word in word_list:
        if len(word) != 0:
            result = result + __word2art(word=word,
                                         font=font,
                                         chr_ignore=chr_ignore,
                                         letters=letters)
    return result
1000495
def _font(size):
        
        # path = '/usr/share/fonts/wenquanyi/wqy-microhei/wqy-microhei.ttc'
        path = os.path.join(
            os.path.dirname(__file__), 'data', "wqy-microhei.ttc")
        return ImageFont.truetype(path, size=int(0.65 * size), index=0)
950753
def text(self, text, x, y, width, height, color, font):
        
        # Helper function.
        def chop(word):
            """
            Take a word longer than the bounding box's width and chop off as many
            letters in the beginning as fit, followed by an ellipsis.
            """
            total_str = ""
            for c in word:
                _, _, total_width, _, _, _ = self.context.text_extents(total_str + c + "…")
                if total_width >= width:
                    return total_str + "…"
                total_str += c
            assert not "Should not be here, else 'word' fit into the bounding box"
        # Prepare the context for text rendering.
        self.context.set_source_rgb(*color)
        font_name, (font_size, font_slant, font_weight) = (font)
        self.context.select_font_face(font_name, font_slant, font_weight)
        self.context.set_font_size(font_size)
        self.context.set_antialias(cairo.ANTIALIAS_DEFAULT)
        # Get some font metrics.
        font_asc, _, font_height, _, _ = self.context.font_extents()
        # Initialize text cursor to the baseline of the font.
        width, height = self.tx(width), self.ty(height)
        w_x, w_y = self.tx(x), font_asc + self.ty(y)
        # Draw the text one line at a time and ensure the bounding box.
        line = ""
        nlines = 1
        for word in text.split(" "):
            _, _, line_width, _, _, _ = self.context.text_extents(_join(line, word))
            if line_width < width:
                line = _join(line, word)
            else:
                if not line:
                    # First word of the line extends beyond the line: chop and done.
                    self.context.move_to(w_x, w_y)
                    self.context.show_text(chop(word))
                    return nlines, font_height
                else:
                    # Filled a line, render it, and move on to the next line.
                    self.context.move_to(w_x, w_y)
                    self.context.show_text(line)
                    line = word
                    w_y += font_height

                    if w_y > height:
                        return nlines, font_height
                    nlines += 1
        self.context.move_to(w_x, w_y)
        self.context.show_text(line)
        return nlines, font_height
382283
def _raw_print_image(self, line, size, output=None ):
        
        i = 0
        cont = 0
        buffer = ""
        raw = ""

        def __raw(string):
            if output:
                output(string)
            else:
                self._raw(string)
       
        raw += S_RASTER_N
        buffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1], 0)
        raw += buffer.decode('hex')
        buffer = ""

        while i < len(line):
            hex_string = int(line[i:i+8],2)
            buffer += "%02X" % hex_string
            i += 8
            cont += 1
            if cont % 4 == 0:
                raw += buffer.decode("hex")
                buffer = ""
                cont = 0

        return raw
704086
def to_raster(self, vector):
        """"""
        return transform(vector.get_shape(vector.crs), vector.crs, self.crs, dst_affine=~self.affine)
175014
public static byte[] getPixelsBGR(BufferedImage img, int y, int w, byte[] array, int[] temp) {
    final int x = 0;
    final int h = 1;

    assert array.length == temp.length * nrChannels(img);
    assert (temp.length == w);

    int imageType = img.getType();
    Raster raster;
    switch (imageType) {
      case BufferedImage.TYPE_3BYTE_BGR:
      case BufferedImage.TYPE_4BYTE_ABGR:
      case BufferedImage.TYPE_4BYTE_ABGR_PRE:
      case BufferedImage.TYPE_BYTE_GRAY:
        raster = img.getRaster();
        //int ttype= raster.getTransferType();
        raster.getDataElements(x, y, w, h, array);
        break;
      case BufferedImage.TYPE_INT_BGR:
        raster = img.getRaster();
        raster.getDataElements(x, y, w, h, temp);
        ints2bytes(temp, array, 0, 1, 2);  // bgr -->  bgr
        break;
      case BufferedImage.TYPE_INT_RGB:
        raster = img.getRaster();
        raster.getDataElements(x, y, w, h, temp);
        ints2bytes(temp, array, 2, 1, 0);  // rgb -->  bgr
        break;
      case BufferedImage.TYPE_INT_ARGB:
      case BufferedImage.TYPE_INT_ARGB_PRE:
        raster = img.getRaster();
        raster.getDataElements(x, y, w, h, temp);
        ints2bytes(temp, array, 2, 1, 0, 3);  // argb -->  abgr
        break;
      case BufferedImage.TYPE_CUSTOM: // TODO: works for my icon image loader, but else ???
        img.getRGB(x, y, w, h, temp, 0, w);
        ints2bytes(temp, array, 2, 1, 0, 3);  // argb -->  abgr
        break;
      default:
        img.getRGB(x, y, w, h, temp, 0, w);
        ints2bytes(temp, array, 2, 1, 0);  // rgb -->  bgr
        break;
    }

    return array;
  }
697986
def boxed_text_to_image_block(tag):
    ""
    tag_block = OrderedDict()
    image_content = body_block_image_content(first(raw_parser.inline_graphic(tag)))
    tag_block["type"] = "image"
    set_if_value(tag_block, "doi", doi_uri_to_doi(object_id_doi(tag, tag.name)))
    set_if_value(tag_block, "id", tag.get("id"))
    set_if_value(tag_block, "image", image_content)
    # render paragraphs into a caption
    p_tags = raw_parser.paragraph(tag)
    caption_content = []
    for p_tag in p_tags:
        if not raw_parser.inline_graphic(p_tag):
            caption_content.append(body_block_content(p_tag))
    set_if_value(tag_block, "caption", caption_content)
    return tag_block
1003105
def convert(self, text):
        """"""
        # Main function. The order in which other subs are called here is
        # essential. Link and image substitutions need to happen before
        # _EscapeSpecialChars(), so that any *'s or _'s in the <a>
        # and <img> tags get encoded.

        # Clear the global hashes. If we don't clear these, you get conflicts
        # from other articles when generating a page which contains more than
        # one article (e.g. an index page that shows the N most recent
        # articles):
        self.reset()

        if not isinstance(text, unicode):
            #TODO: perhaps shouldn't presume UTF-8 for string input?
            text = unicode(text, 'utf-8')

        if self.use_file_vars:
            # Look for emacs-style file variable hints.
            emacs_vars = self._get_emacs_vars(text)
            if "markdown-extras" in emacs_vars:
                splitter = re.compile("[ ,]+")
                for e in splitter.split(emacs_vars["markdown-extras"]):
                    if '=' in e:
                        ename, earg = e.split('=', 1)
                        try:
                            earg = int(earg)
                        except ValueError:
                            pass
                    else:
                        ename, earg = e, None
                    self.extras[ename] = earg

        # Standardize line endings:
        text = re.sub("\r\n|\r", "\n", text)

        # Make sure $text ends with a couple of newlines:
        text += "\n\n"

        # Convert all tabs to spaces.
        text = self._detab(text)

        # Strip any lines consisting only of spaces and tabs.
        # This makes subsequent regexen easier to write, because we can
        # match consecutive blank lines with /\n+/ instead of something
        # contorted like /[ \t]*\n+/ .
        text = self._ws_only_line_re.sub("", text)

        # strip metadata from head and extract
        if "metadata" in self.extras:
            text = self._extract_metadata(text)

        text = self.preprocess(text)

        if self.safe_mode:
            text = self._hash_html_spans(text)

        # Turn block-level HTML blocks into hash entries
        text = self._hash_html_blocks(text, raw=True)

        # Strip link definitions, store in hashes.
        if "footnotes" in self.extras:
            # Must do footnotes first because an unlucky footnote defn
            # looks like a link defn:
            #   [^4]: this "looks like a link defn"
            text = self._strip_footnote_definitions(text)
        text = self._strip_link_definitions(text)

        text = self._run_block_gamut(text)

        if "footnotes" in self.extras:
            text = self._add_footnotes(text)

        text = self.postprocess(text)

        text = self._unescape_special_chars(text)

        if self.safe_mode:
            text = self._unhash_html_spans(text)

        if "nofollow" in self.extras:
            text = self._a_nofollow.sub(r'<\1 rel="nofollow"\2', text)

        text += "\n"

        rv = UnicodeWithAttrs(text)
        if "toc" in self.extras:
            rv._toc = self._toc
        if "metadata" in self.extras:
            rv.metadata = self.metadata
        return rv
244603
def add_text_to_image(fname, txt, opFilename):
    
    ft = ImageFont.load("T://user//dev//src//python//_AS_LIB//timR24.pil")
    #wh = ft.getsize(txt)
    print("Adding text ", txt, " to ", fname, " pixels wide to file " , opFilename)
    im = Image.open(fname)
    draw = ImageDraw.Draw(im)
    draw.text((0, 0), txt, fill=(0, 0, 0), font=ft)
    del draw  
    im.save(opFilename)
915416
def text_width(text):
    """"""
    (xmin, xmax, d1, d2) = get_dimension(text)
    return xmax - xmin
1080928
def md(self, text=TEXT, float_format="%.2g"):
        
        cols = self._data.columns
        hl = pd.DataFrame([["---"] * len(cols)], index=["---"], columns=cols)
        df = pd.concat([hl, self._data])
        return df.to_csv(sep='|', index=True, float_format=float_format)
1338436
private byte[] convert(Bitmap bitmap, String format) {
        final int width = bitmap.getWidth();
        final int height = bitmap.getHeight();

        DataBuffer buffer = new DataBufferByte(bitmap.getPixels(), bitmap.getLength());
        WritableRaster writableRaster = Raster.createPackedRaster(buffer, width, height, width, MASKS, null);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        bufferedImage.setData(writableRaster);

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ImageIO.write(bufferedImage, format, outputStream);
            outputStream.close();
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
462970
def _pixel_data(image):
    
    # Test for PIL.Image and numpy.ndarray without requiring that cv2 or PIL
    # are installed.
    if 'PIL.' in str(type(image)):
        pixels = image.tobytes()
        width, height = image.size
    elif 'numpy.ndarray' in str(type(image)):
        if 'uint8' != str(image.dtype):
            image = image.astype('uint8')
        try:
            pixels = image.tobytes()
        except AttributeError:
            # `numpy.ndarray.tobytes()` introduced in `numpy` 1.9.0 - use the
            # older `tostring` method.
            pixels = image.tostring()
        height, width = image.shape[:2]
    else:
        # image should be a tuple (pixels, width, height)
        pixels, width, height = image

        # Check dimensions
        if 0 != len(pixels) % (width * height):
            raise PyLibDMTXError(
                (
                    'Inconsistent dimensions: image data of {0} bytes is not '
                    'divisible by (width x height = {1})'
                ).format(len(pixels), (width * height))
            )

    # Compute bits-per-pixel
    bpp = 8 * len(pixels) // (width * height)
    if bpp not in _PACK_ORDER:
        raise PyLibDMTXError(
            'Unsupported bits-per-pixel: [{0}] Should be one of {1}'.format(
                bpp, sorted(_PACK_ORDER.keys())
            )
        )

    return pixels, width, height, bpp
130166
def _load_raster_text(self, raster_path):
        
        # Open file and read plain text into text field
        with open(raster_path, 'r') as f:
            self.rasterText = f.read()

        # Retrieve metadata from header
        lines = self.rasterText.split('\n')
        for line in lines[0:6]:
            spline = line.split()

            if 'north' in spline[0].lower():
                self.north = float(spline[1])
            elif 'south' in spline[0].lower():
                self.south = float(spline[1])
            elif 'east' in spline[0].lower():
                self.east = float(spline[1])
            elif 'west' in spline[0].lower():
                self.west = float(spline[1])
            elif 'rows' in spline[0].lower():
                self.rows = int(spline[1])
            elif 'cols' in spline[0].lower():
                self.columns = int(spline[1])
492664
def pixels=(values)
      raise ArgumentError, "The given argument does not respond to #to_a (got an argument of class #{values.class})" unless values.respond_to?(:to_a)
      if values.class.ancestors.to_s.include?('NArray')
        # With an NArray argument, make sure that it gets properly converted to an Array:
        if values.shape.length > 2
          # For a 3D NArray we need to rearrange to ensure that the pixels get their
          # proper order when converting to an ordinary Array instance:
          narr = Numo::Int16.zeros(values.shape[0], values.shape[1] * values.shape[2])
          values.shape[0].times do |i|
            narr[i, true] = values[i, true, true].reshape(values.shape[1] * values.shape[2])
          end
          values = narr
        end
      end
      # Encode the pixel data:
      bin = encode_pixels(values.to_a.flatten)
      # Write the binary data to the Pixel Data Element:
      write_pixels(bin)
    end