Writes a barcode PNG image.

 opts:
 :subset - specify the Code128 subset to use ('A', 'B', or 'C').
 remaining options passed through to PNGOutputter.
13693
def create_barcode(opts = {})
      path = barcode_path
      FileUtils.mkdir_p File.dirname(path)
      File.open(path, 'wb') do |f|
        f.write barcode(opts).to_png(self.class.options.merge(opts))
      end
      FileUtils.chmod(0666 &~ File.umask, path)
    end
1068711
def parse_buffer_to_png(data):
    

    images = []

    c1 = 0
    c2 = 0
    data_len = len(data)
    while c1 < data_len:
        # IEND can appear in a PNG without being the actual end
        if data[c2:c2 + 4] == b'IEND' and (c2 + 8 == data_len or data[c2+9:c2+12] == b'PNG'):
            images.append(Image.open(BytesIO(data[c1:c2 + 8])))
            c1 = c2 + 8
            c2 = c1
        c2 += 1

    return images
180663
def write_gif_to_file(self, fp, images, durations, loops, xys, disposes):
        

        # Obtain palette for all images and count each occurance
        palettes, occur = [], []
        for im in images:
            palettes.append(getheader(im)[1])
        for palette in palettes:
            occur.append(palettes.count(palette))

        # Select most-used palette as the global one (or first in case no max)
        print palettes, occur
        global_palette = palettes[occur.index(max(occur))]

        # Init
        frames = 0
        first_frame = True

        for im, palette in zip(images, palettes):

            if first_frame:
                # Write header

                # Gather info
                header = self.get_header_anim(im)
                appext = self.get_app_ext(loops)

                # Write
                fp.write(header)
                fp.write(global_palette)
                fp.write(appext)

                # Next frame is not the first
                first_frame = False

            if True:
                # Write palette and image data

                # Gather info
                data = getdata(im)
                imdes, data = data[0], data[1:]

                transparent_flag = 0
                if self.transparency:
                    transparent_flag = 1

                graphext = self.get_graphics_control_ext(
                    durations[frames],
                    disposes[frames],
                    transparent_flag=transparent_flag,
                    transparency_index=255)

                # Make image descriptor suitable for using 256 local color palette
                lid = self.get_image_descriptor(im, xys[frames])

                # Write local header
                if (palette != global_palette) or (disposes[frames] != 2):
                    # Use local color palette
                    fp.write(graphext)
                    fp.write(lid)  # write suitable image descriptor
                    fp.write(palette)  # write local color table
                    fp.write('\x08')  # LZW minimum size code
                else:
                    # Use global color palette
                    fp.write(graphext)
                    fp.write(imdes)  # write suitable image descriptor

                # Write image data
                for d in data:
                    fp.write(d)

            # Prepare for next round
            frames = frames + 1

        fp.write(";")  # end gif
        return frames
435716
def hexdump(src, length=8, colorize=False):
    
    if not src:
        return str(src)
    if type(src) is not bytes:
        raise yubico_exception.InputError('Hexdump \'src\' must be bytestring (got %s)' % type(src))
    offset = 0
    result = ''
    for this in group(src, length):
        if colorize:
            last, this = this[-1], this[:-1]
            colors = DumpColors()
            color = colors.get('RESET')
            if ord_byte(last) & yubikey_defs.RESP_PENDING_FLAG:
                # write to key
                color = colors.get('BLUE')
            elif ord_byte(last) & yubikey_defs.SLOT_WRITE_FLAG:
                color = colors.get('GREEN')
            hex_s = color + ' '.join(["%02x" % ord_byte(x) for x in this]) + colors.get('RESET')
            hex_s += " %02x" % ord_byte(last)
        else:
            hex_s = ' '.join(["%02x" % ord_byte(x) for x in this])
        result += "%04X   %s\n" % (offset, hex_s)
        offset += length
    return result
268254
def imgwriteincr(fn: Path, imgs, imgslice):
    
    if isinstance(imgslice, int):
        if imgslice and not (imgslice % 2000):
            print(f'appending images {imgslice} to {fn}')

    if isinstance(fn, Path):
        # avoid accidental overwriting of source file due to misspecified command line
        assert fn.suffix == '.h5', 'Expecting to write .h5 file'

        with h5py.File(fn, 'r+') as f:
            f['/rawimg'][imgslice, :, :] = imgs
    elif isinstance(fn, h5py.File):
        f['/rawimg'][imgslice, :, :] = imgs
    else:
        raise TypeError(
            f'{fn} must be Path or h5py.File instead of {type(fn)}')
1297310
def img2code(self, key, img):
        """"""

        code_template = \
            "wx.ImageFromData({width}, {height}, " + \
            "bz2.decompress(base64.b64decode('{data}'))).ConvertToBitmap()"

        code_alpha_template = \
            "wx.ImageFromDataWithAlpha({width}, {height}, " + \
            "bz2.decompress(base64.b64decode('{data}')), " + \
            "bz2.decompress(base64.b64decode('{alpha}'))).ConvertToBitmap()"

        data = base64.b64encode(bz2.compress(img.GetData(), 9))

        if img.HasAlpha():
            alpha = base64.b64encode(bz2.compress(img.GetAlphaData(), 9))
            code_str = code_alpha_template.format(
                width=img.GetWidth(), height=img.GetHeight(),
                data=data, alpha=alpha)
        else:
            code_str = code_template.format(width=img.GetWidth(),
                                            height=img.GetHeight(), data=data)

        return code_str
693120
def write_ImageMapLine(tlx, tly, brx, bry, w, h, dpi, chr, segment_start, segment_end):
    
    tlx, brx = [canvas2px(x, w, dpi) for x in (tlx, brx)]
    tly, bry = [canvas2px(y, h, dpi) for y in (tly, bry)]
    chr, bac_list = chr.split(':')
    return '<area shape="rect" coords="' + \
           ",".join(str(x) for x in (tlx, tly, brx, bry)) \
           + '" href="#' + chr + '"' \
           + ' title="' + chr + ':' + str(segment_start) + '..' + str(segment_end) + '"' \
           + ' />'
1250708
def optimize_png_file(f, o=None):
    
    if isinstance(f, basestring):
        if o is None:
            o = f
        else:
            assert isinstance(o, basestring)
        try:
            subprocess.check_call(['pngquant', '--force', '--output', o, f])
        except subprocess.CalledProcessError:
            return False
        return True
    if not hasattr(f, 'read'):
        raise RuntimeError
    if o is None:
        o = f
    else:
        if not hasattr(f, 'write'):
            raise RuntimeError
    f.seek(0)
    try:
        p = subprocess.Popen(['pngquant', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        r = p.communicate(f.read())[0]
    except IOError:
        r = None
    if r:
        truncate_file(o)
        o.write(r)
        return True
    return False
742192
public void escape(Pointer _src, int len) {
        byte[] bsrc = _src.buffer;
        int src = _src.start;
        for(int i=0; i<len; i++) {
            int curr = (int)bsrc[src+i]&0xFF;

            if(curr < 0x20 || (0x7E < curr)) {
                write(BACKSLASH, 1);
                if(curr == 0) {
                    write(ZERO, 1);
                } else {
                    write(X, 1);
                    write(hex_table.withStart((curr & 0xF0) >> 4), 1);
                    write(hex_table.withStart(curr & 0x0F), 1);
                }
            } else {
                write(_src.withStart(src+i), 1);
                if(curr == '\\') {
                    write(BACKSLASH, 1);
                }
            }
        }
    }
1223713
def writeGifToFile(self, fp, images, durations, loops, xys, disposes):
        
        # Obtain palette for all images and count each occurance
        palettes, occur = [], []
        for im in images:
            header, usedPaletteColors = getheader(im)
            palettes.append(header[-1])  # Last part of the header is the frame palette
        for palette in palettes:
            occur.append(palettes.count(palette))

        # Select most-used palette as the global one (or first in case no max)
        globalPalette = palettes[occur.index(max(occur))]

        # Init
        frames = 0
        firstFrame = True

        for im, palette in zip(images, palettes):

            if firstFrame:
                # Write header

                # Gather info
                header = self.getheaderAnim(im)
                appext = self.getAppExt(loops)

                # Write
                fp.write(header)
                fp.write(globalPalette)
                fp.write(appext)

                # Next frame is not the first
                firstFrame = False

            if True:
                # Write palette and image data

                # Gather info
                data = getdata(im)

                imdes, data = b''.join(data[:-2]), data[-2:]
                graphext = self.getGraphicsControlExt(durations[frames], disposes[frames])
                # Make image descriptor suitable for using 256 local color palette
                lid = self.getImageDescriptor(im, xys[frames])

                # Write local header
                if (palette != globalPalette) or (disposes[frames] != 2):
                    # Use local color palette
                    fp.write(graphext)
                    fp.write(lid)  # write suitable image descriptor
                    fp.write(palette)  # write local color table
                    fp.write('\x08')  # LZW minimum size code
                else:
                    # Use global color palette
                    fp.write(graphext)
                    fp.write(imdes)  # write suitable image descriptor

                for d in data:
                    fp.write(d)

            # Prepare for next round
            frames = frames + 1

        fp.write(";")  # end gif
        return frames
1085142
def write(self, image, options, thumbnail):
        

        args = settings.THUMBNAIL_VIPSTHUMBNAIL.split(' ')
        args.append(image['source'])

        for k in image['options']:
            v = image['options'][k]
            args.append('--%s' % k)
            if v is not None:
                args.append('%s' % v)

        suffix = '.%s' % EXTENSIONS[options['format']]

        write_options = []
        if options['format'] == 'JPEG' and options.get(
                'progressive', settings.THUMBNAIL_PROGRESSIVE):
            write_options.append("interlace")

        if options['quality']:
            if options['format'] == 'JPEG':
                write_options.append("Q=%d" % options['quality'])

        with NamedTemporaryFile(suffix=suffix, mode='rb') as fp:
            # older vipsthumbails used -o, this was renamed to -f in 8.0, use
            # -o here for commpatibility
            args.append("-o")
            args.append(fp.name + "[%s]" % ",".join(write_options))

            args = map(smart_str, args)
            p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            p.wait()
            out, err = p.communicate()

            if err:
                raise Exception(err)

            thumbnail.write(fp.read())
557674
def save_png(opts = {})
      range = Args::CardRange.new(opts[:range], deck_size: size)
      batch = Args::SaveBatch.new.load!(opts, expand_by: size, layout: layout, dpi: dpi)
      @progress_bar.start("Saving PNGs to #{batch.summary}", size) do |bar|
        range.each do |i|
          @cards[i].save_png(batch[i])
          bar.increment
        end
      end
    end
269594
def show_letter(
            self,
            s,
            text_colour=[255, 255, 255],
            back_colour=[0, 0, 0]
        ):
        

        if len(s) > 1:
            raise ValueError('Only one character may be passed into this method')
        # We must rotate the pixel map left through 90 degrees when drawing
        # text, see _load_text_assets
        previous_rotation = self._rotation
        self._rotation -= 90
        if self._rotation < 0:
            self._rotation = 270
        dummy_colour = [None, None, None]
        pixel_list = [dummy_colour] * 8
        pixel_list.extend(self._get_char_pixels(s))
        pixel_list.extend([dummy_colour] * 16)
        coloured_pixels = [
            text_colour if pixel == [255, 255, 255] else back_colour
            for pixel in pixel_list
        ]
        self.set_pixels(coloured_pixels)
        self._rotation = previous_rotation
1175827
def tonet(self, outfile):
        
        
        self.checkforpilimage()
        if self.verbose :
            print "Writing image to %s...\n%i x %i pixels, mode %s" % (outfile, self.pilimage.size[0], self.pilimage.size[1], self.pilimage.mode)
        self.pilimage.save(outfile, "PNG")
208257
public static void writePng(Image image, ImageOutputStream destImageStream) throws IORuntimeException {
		write(image, IMAGE_TYPE_PNG, destImageStream);
	}
1110572
def write_array(self, outfile, pixels):
        

        if self.interlace:
            if type(pixels) != array:
                # Coerce to array type
                fmt = 'BH'[self.bitdepth > 8]
                pixels = array(fmt, pixels)
            self.write_passes(outfile, self.array_scanlines_interlace(pixels))
        else:
            self.write_passes(outfile, self.array_scanlines(pixels))
244626
void encode(Bitmap bitmap, BufferedSink sink) throws IOException {
    int height = bitmap.height();
    int width = bitmap.width();

    int bytesPerPixel = 3;
    int rowByteCountWithoutPadding = (bytesPerPixel * width);
    int rowByteCount = ((rowByteCountWithoutPadding + 3) / 4) * 4;
    int pixelDataSize = rowByteCount * height;
    int bmpHeaderSize = 14;
    int dibHeaderSize = 40;

    // BMP Header
    sink.writeUtf8("BM"); // ID.
    sink.writeIntLe(bmpHeaderSize + dibHeaderSize + pixelDataSize); // File size.
    sink.writeShortLe(0); // Unused.
    sink.writeShortLe(0); // Unused.
    sink.writeIntLe(bmpHeaderSize + dibHeaderSize); // Offset of pixel data.

    // DIB Header
    sink.writeIntLe(dibHeaderSize);
    sink.writeIntLe(width);
    sink.writeIntLe(height);
    sink.writeShortLe(1);  // Color plane count.
    sink.writeShortLe(bytesPerPixel * Byte.SIZE);
    sink.writeIntLe(0);    // No compression.
    sink.writeIntLe(16);   // Size of bitmap data including padding.
    sink.writeIntLe(2835); // Horizontal print resolution in pixels/meter. (72 dpi).
    sink.writeIntLe(2835); // Vertical print resolution in pixels/meter. (72 dpi).
    sink.writeIntLe(0);    // Palette color count.
    sink.writeIntLe(0);    // 0 important colors.

    // Pixel data.
    for (int y = height - 1; y >= 0; y--) {
      for (int x = 0; x < width; x++) {
        sink.writeByte(bitmap.blue(x, y));
        sink.writeByte(bitmap.green(x, y));
        sink.writeByte(bitmap.red(x, y));
      }

      // Padding for 4-byte alignment.
      for (int p = rowByteCountWithoutPadding; p < rowByteCount; p++) {
        sink.writeByte(0);
      }
    }
  }