write_gif_to_file(fp, images, durations, loops, xys, disposes)

        Given a set of images writes the bytes to the specified stream.
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
241805
def write(self, buf):
        """"""
        if not isinstance(buf, six.binary_type):
            raise TypeError('buf: must be a bytes instance')
        # Be careful not to write zero-length chunks as they indicate the end of a body.
        if len(buf) == 0:
            return
        if self._content_length and self._bytes_written > self._content_length:
            raise RuntimeError('wrote too many bytes ({} > {})'
                                    .format(self._bytes_written, self._content_length))
        self._bytes_written += len(buf)
        if self._chunked:
            buf = create_chunk(buf)
        self._protocol.writer.write(buf)
1095812
def _write(self, stream, text, byte_order):
        '''
        

        '''
        if text:
            self._write_txt(stream)
        else:
            if self._have_list:
                # There are list properties, so serialization is
                # slightly complicated.
                self._write_bin(stream, byte_order)
            else:
                # no list properties, so serialization is
                # straightforward.
                stream.write(self.data.astype(self.dtype(byte_order),
                                              copy=False).data)
483582
function GifRecorder(mediaStream) {
    if (typeof GIFEncoder === 'undefined') {
        throw 'Please link: https://cdn.webrtc-experiment.com/gif-recorder.js';
    }

    // void start(optional long timeSlice)
    // timestamp to fire "ondataavailable"
    this.start = function(timeSlice) {
        timeSlice = timeSlice || 1000;

        var imageWidth = this.videoWidth || 320;
        var imageHeight = this.videoHeight || 240;

        canvas.width = video.width = imageWidth;
        canvas.height = video.height = imageHeight;

        // external library to record as GIF images
        gifEncoder = new GIFEncoder();

        // void setRepeat(int iter)
        // Sets the number of times the set of GIF frames should be played.
        // Default is 1; 0 means play indefinitely.
        gifEncoder.setRepeat(0);

        // void setFrameRate(Number fps)
        // Sets frame rate in frames per second.
        // Equivalent to setDelay(1000/fps).
        // Using "setDelay" instead of "setFrameRate"
        gifEncoder.setDelay(this.frameRate || this.speed || 200);

        // void setQuality(int quality)
        // Sets quality of color quantization (conversion of images to the
        // maximum 256 colors allowed by the GIF specification).
        // Lower values (minimum = 1) produce better colors,
        // but slow processing significantly. 10 is the default,
        // and produces good color mapping at reasonable speeds.
        // Values greater than 20 do not yield significant improvements in speed.
        gifEncoder.setQuality(this.quality || 1);

        // Boolean start()
        // This writes the GIF Header and returns false if it fails.
        gifEncoder.start();

        startTime = Date.now();

        function drawVideoFrame(time) {
            if (isPaused) {
                setTimeout(drawVideoFrame, 500, time);
                return;
            }

            lastAnimationFrame = requestAnimationFrame(drawVideoFrame);

            if (typeof lastFrameTime === undefined) {
                lastFrameTime = time;
            }

            // ~10 fps
            if (time - lastFrameTime < 90) {
                return;
            }

            if (video.paused) {
                video.play(); // Android
            }

            context.drawImage(video, 0, 0, imageWidth, imageHeight);

            gifEncoder.addFrame(context);

            // console.log('Recording...' + Math.round((Date.now() - startTime) / 1000) + 's');
            // console.log("fps: ", 1000 / (time - lastFrameTime));

            lastFrameTime = time;
        }

        lastAnimationFrame = requestAnimationFrame(drawVideoFrame);

        timeout = setTimeout(doneRecording, timeSlice);
    };

    function doneRecording() {
        endTime = Date.now();

        var gifBlob = new Blob([new Uint8Array(gifEncoder.stream().bin)], {
            type: 'image/gif'
        });
        self.ondataavailable(gifBlob);

        // todo: find a way to clear old recorded blobs
        gifEncoder.stream().bin = [];
    }

    this.stop = function() {
        if (lastAnimationFrame) {
            cancelAnimationFrame(lastAnimationFrame);
            clearTimeout(timeout);
            doneRecording();
            this.onstop();
        }
    };

    this.onstop = function() {};

    var isPaused = false;

    this.pause = function() {
        isPaused = true;
    };

    this.resume = function() {
        isPaused = false;
    };

    this.ondataavailable = function() {};
    this.onstop = function() {};

    // Reference to itself
    var self = this;

    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');

    var video = document.createElement('video');
    video.muted = true;
    video.autoplay = true;
    video.src = URL.createObjectURL(mediaStream);
    video.play();

    var lastAnimationFrame = null;
    var startTime, endTime, lastFrameTime;

    var gifEncoder;
    var timeout;
}
420008
def writeBytes(self, s):
        
        l = len(s)

        if l > 0xffff:
            self.writeType(TYPE_LONGSTRING)
        else:
            self.writeType(TYPE_STRING)

        if l > 0xffff:
            self.stream.write_ulong(l)
        else:
            self.stream.write_ushort(l)

        self.stream.write(s)
285892
def write(self, chars, output, format='png'):
        
        im = self.generate_image(chars)
        return im.save(output, format=format)
165424
def write_stream(self, stream, left_chunk, right_chunk, volume):
        '''
        
        '''
        if len(left_chunk) != len(right_chunk):
            raise ValueError()

        for i in range(len(left_chunk)):
            chunk = (left_chunk[i] + right_chunk[i]) * volume
            data = struct.pack("2f", chunk, chunk)
            stream.write(data)
997488
public static boolean writeBytesToFile(byte[] bytes, File f) {
        try {
            FileOutputStream fout = new FileOutputStream(f);
            fout.write(bytes);
            fout.close();
        } catch (Exception e) {
            System.out.println("Error writing byte[] to file: "
                    + e.getMessage());
            return false;
        }
        return true;
    }
1164649
public static void saveImage(BufferedImage image, OutputStream output) throws IOException
    {
        ImageIO.write(image, "png", output);
    }
1009945
def get_gif_frames(img):
    
    gif_frames = []
    n = 0
    while img:
        if img.mode != "RGB":
            image = img.convert(mode="RGB")
        else:
            image = img
        gif_frames.append(image)
        n += 1
        try:
            img.seek(n)
        except EOFError:
            break
    return gif_frames
683636
function (fn) {

		var writeBuffer = new streamBuffers.WritableStreamBuffer({
			initialSize: (100 * 1024), incrementAmount: (10 * 1024)
		});

		fn = fn || function () {};

		this._image.pack().pipe(writeBuffer).once('close', function () {
			this._image.removeListener('error', fn);
			fn(undefined, writeBuffer.getContents());
		}.bind(this)).once('error', function (err) {
			this._image.removeListener('close', fn);
			fn(err);
		}.bind(this));
	}
393829
def readGif(filename, asNumpy=True):
    

    # Check PIL
    if PIL is None:
        raise RuntimeError("Need PIL to read animated gif files.")

    # Check Numpy
    if np is None:
        raise RuntimeError("Need Numpy to read animated gif files.")

    # Check whether it exists
    if not os.path.isfile(filename):
        raise IOError('File not found: ' + str(filename))

    # Load file using PIL
    pilIm = PIL.Image.open(filename)
    pilIm.seek(0)

    # Read all images inside
    images = []
    try:
        while True:
            # Get image as numpy array
            tmp = pilIm.convert()  # Make without palette
            a = np.asarray(tmp)
            if len(a.shape) == 0:
                raise MemoryError("Too little memory to convert PIL image to array")
            # Store, and next
            images.append(a)
            pilIm.seek(pilIm.tell() + 1)
    except EOFError:
        pass

    # Convert to normal PIL images if needed
    if not asNumpy:
        images2 = images
        images = []
        for im in images2:
            images.append(PIL.Image.fromarray(im))

    # Done
    return images
10675
public static boolean write(Image image, String imageType, ImageOutputStream destImageStream, float quality) throws IORuntimeException {
		if (StrUtil.isBlank(imageType)) {
			imageType = IMAGE_TYPE_JPG;
		}

		final ImageWriter writer = getWriter(image, imageType);
		return write(toBufferedImage(image, imageType), writer, destImageStream, quality);
	}
340550
public void write(byte []buf, int offset, int length, boolean isEnd)
    throws IOException
  {
    if (_stream != null)
      _stream.write(buf, offset, length, isEnd);
  }
109912
public static void writePng(Image image, OutputStream out) throws IORuntimeException {
		write(image, IMAGE_TYPE_PNG, out);
	}
248770
def write_file(self, blob, dest):
        '''
        
        '''
        with salt.utils.files.fopen(dest, 'wb+') as fp_:
            blob.stream_data(fp_)
1146256
def write(self, data):
    
    ctx = context.get()
    if len(data) != 2:
      logging.error("Got bad tuple of length %d (2-tuple expected): %s",
                    len(data), data)

    try:
      key = str(data[0])
      value = str(data[1])
    except TypeError:
      logging.error("Expecting a tuple, but got %s: %s",
                    data.__class__.__name__, data)

    file_index = key.__hash__() % len(self._filehandles)

    # Work-around: Since we don't have access to the context in the to_json()
    # function, but we need to flush each pool before we serialize the
    # filehandle, we rely on a member variable instead of using context for
    # pool management.
    pool = self._pools[file_index]
    if pool is None:
      filehandle = self._filehandles[file_index]
      pool = output_writers.GCSRecordsPool(filehandle=filehandle, ctx=ctx)
      self._pools[file_index] = pool

    proto = kv_pb.KeyValue()
    proto.set_key(key)
    proto.set_value(value)
    pool.append(proto.Encode())