Convert canvas to GIF bytes
779035
def toGIF(self, **attribs):
        
        im = self.toPIL(**attribs)
        sfile = io.BytesIO()
        im.save(sfile, format="gif")
        return sfile.getvalue()
694099
function stringToBytes(str) {
  var bytes = new Array();
  var len, c;
  len = str.length;
  for (var i = 0; i < len; i++) {
    c = str.charCodeAt(i);
    if (c >= 0x010000 && c <= 0x10FFFF) {
      bytes.push(((c >> 18) & 0x07) | 0xF0);
      bytes.push(((c >> 12) & 0x3F) | 0x80);
      bytes.push(((c >> 6) & 0x3F) | 0x80);
      bytes.push((c & 0x3F) | 0x80);
    } else if (c >= 0x000800 && c <= 0x00FFFF) {
      bytes.push(((c >> 12) & 0x0F) | 0xE0);
      bytes.push(((c >> 6) & 0x3F) | 0x80);
      bytes.push((c & 0x3F) | 0x80);
    } else if (c >= 0x000080 && c <= 0x0007FF) {
      bytes.push(((c >> 6) & 0x1F) | 0xC0);
      bytes.push((c & 0x3F) | 0x80);
    } else {
      bytes.push(c & 0xFF);
    }
  }
  return bytes;

}
798125
function storedPixelDataToImageData (image) {
  const minPixelValue = image.minPixelValue;
  let canvasImageDataIndex = 0;
  let storedPixelDataIndex = 0;
  // Only 3 channels, since we use WebGL's RGB texture format
  const numStoredPixels = image.width * image.height * 4;
  const numOutputPixels = image.width * image.height * 3;
  const storedPixelData = image.getPixelData();
  const data = new Uint8Array(numOutputPixels);

  // NOTE: As of Nov 2014, most javascript engines have lower performance when indexing negative indexes.
  // We have a special code path for this case that improves performance.  Thanks to @jpambrun for this enhancement
  if (minPixelValue < 0) {
    while (storedPixelDataIndex < numStoredPixels) {
      data[canvasImageDataIndex++] = storedPixelData[storedPixelDataIndex++] + (-minPixelValue); // Red
      data[canvasImageDataIndex++] = storedPixelData[storedPixelDataIndex++] + (-minPixelValue); // Green
      data[canvasImageDataIndex++] = storedPixelData[storedPixelDataIndex++] + (-minPixelValue); // Blue
      storedPixelDataIndex += 1; // The stored pixel data has 4 channels
    }
  } else {
    while (storedPixelDataIndex < numStoredPixels) {
      data[canvasImageDataIndex++] = storedPixelData[storedPixelDataIndex++]; // Red
      data[canvasImageDataIndex++] = storedPixelData[storedPixelDataIndex++]; // Green
      data[canvasImageDataIndex++] = storedPixelData[storedPixelDataIndex++]; // Blue
      storedPixelDataIndex += 1; // The stored pixel data has 4 channels
    }
  }

  return data;
}
958101
def pixbuf_to_cairo_slices(pixbuf):
    
    assert pixbuf.get_colorspace() == gdk_pixbuf.GDK_COLORSPACE_RGB
    assert pixbuf.get_n_channels() == 3
    assert pixbuf.get_bits_per_sample() == 8
    width = pixbuf.get_width()
    height = pixbuf.get_height()
    rowstride = pixbuf.get_rowstride()
    pixels = ffi.buffer(pixbuf.get_pixels(), pixbuf.get_byte_length())
    # TODO: remove this when cffi buffers support slicing with a stride.
    pixels = pixels[:]

    # Convert GdkPixbuf’s big-endian RGBA to cairo’s native-endian ARGB
    cairo_stride = ImageSurface.format_stride_for_width(
        constants.FORMAT_RGB24, width)
    data = bytearray(cairo_stride * height)
    big_endian = sys.byteorder == 'big'
    pixbuf_row_length = width * 3  # stride == row_length + padding
    cairo_row_length = width * 4  # stride == row_length + padding
    alpha = b'\xff' * width  # opaque
    for y in range(height):
        offset = rowstride * y
        end = offset + pixbuf_row_length
        red = pixels[offset:end:3]
        green = pixels[offset + 1:end:3]
        blue = pixels[offset + 2:end:3]

        offset = cairo_stride * y
        end = offset + cairo_row_length
        if big_endian:  # pragma: no cover
            data[offset:end:4] = alpha
            data[offset + 1:end:4] = red
            data[offset + 2:end:4] = green
            data[offset + 3:end:4] = blue
        else:
            data[offset + 3:end:4] = alpha
            data[offset + 2:end:4] = red
            data[offset + 1:end:4] = green
            data[offset:end:4] = blue

    data = array('B', data)
    return ImageSurface(constants.FORMAT_RGB24,
                        width, height, data, cairo_stride)
422443
function copyImageDataWithCanvas ( imageData ) {
	const canvas = new Canvas( imageData.width, imageData.height );
	const ctx = canvas.getContext( '2d' );
	ctx.putImageData( imageData, 0, 0 );
				
	return ctx.getImageData( 0, 0, imageData.width, imageData.height );
}
294596
def base64ToImage(imgData, out_path, out_file):
        
        fh = open(os.path.join(out_path, out_file), "wb")
        fh.write(imgData.decode('base64'))
        fh.close()
        del fh
        return os.path.join(out_path, out_file)
37453
def get_gif(api_key, gif_id):
    ''''''
    url = 'http://api.giphy.com/v1/gifs/{}?api_key={}'.format(gif_id, api_key)
    r = urlopen(url)

    return json.loads(r.read().decode('utf-8'))
1158049
def fig_to_src(figure, image_format='png', dpi=80):
    
    if image_format == 'png':
        f = io.BytesIO()
        figure.savefig(f, format=image_format, dpi=dpi)
        f.seek(0)
        return png_to_src(f.read())

    elif image_format == 'svg':
        f = io.StringIO()
        figure.savefig(f, format=image_format, dpi=dpi)
        f.seek(0)
        return svg_to_src(f.read())
657125
function bytesToWords(input) {
  var i;
  var output = [];
  output[(input.length >> 2) - 1] = undefined;
  for (i = 0; i < output.length; i += 1) {
    output[i] = 0;
  }
  var length8 = input.length * 8;
  for (i = 0; i < length8; i += 8) {
    output[i >> 5] |= (input[(i / 8)] & 0xFF) << (i % 32);
  }

  return output;
}
632853
function processFrame(imageBitmap) {
  canvas.width = imageBitmap.width;
  canvas.height = imageBitmap.height;
  canvas.getContext('2d').drawImage(imageBitmap, 0, 0);
}
180756
function (canvasEl) {
       var context = canvasEl.getContext('2d'),
           imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
           data = imageData.data,
           iLen = imageData.width,
           jLen = imageData.height,
           index, average, i, j;

       for (i = 0; i < iLen; i++) {
         for (j = 0; j < jLen; j++) {

           index = (i * 4) * jLen + (j * 4);
           average = (data[index] + data[index + 1] + data[index + 2]) / 3;

           data[index]     = average;
           data[index + 1] = average;
           data[index + 2] = average;
         }
       }

       context.putImageData(imageData, 0, 0);
     }
957330
function unpackPNG(w, h, c, str) {
  var canvas = document.createElement("canvas")
  canvas.width = h
  canvas.height = w
  var img = new Image()
  img.src = "data:image/png;base64," + str
  var context = canvas.getContext("2d")
  context.drawImage(img, 0, 0)
  var pixels = context.getImageData(0, 0, h, w)
  return ndarray(pixels.data, [w, h, c], [4, 4*w, 1], 0)
}
967631
function( shotBuffer ) {

        var scope = this;

        var image = "data:image/"
            + scope.opts.output
            + ";base64,"
            + new Buffer( shotBuffer ).toString( "base64" );

        return image;

    }
53406
private void decodeBitmapData(GifFrame frame) {
        workBufferSize = 0;
        workBufferPosition = 0;
        if (frame != null) {
            // Jump to the frame start position.
            rawData.position(frame.bufferFrameStart);
        }

        int npix = (frame == null) ? header.width * header.height : frame.iw * frame.ih;
        int available, clear, codeMask, codeSize, endOfInformation, inCode, oldCode, bits, code, count,
                i, datum,
                dataSize, first, top, bi, pi;

        if (mainPixels == null || mainPixels.length < npix) {
            // Allocate new pixel array.
            mainPixels = bitmapProvider.obtainByteArray(npix);
        }
        if (prefix == null) {
            prefix = new short[MAX_STACK_SIZE];
        }
        if (suffix == null) {
            suffix = new byte[MAX_STACK_SIZE];
        }
        if (pixelStack == null) {
            pixelStack = new byte[MAX_STACK_SIZE + 1];
        }

        // Initialize GIF data stream decoder.
        dataSize = readByte();
        clear = 1 << dataSize;
        endOfInformation = clear + 1;
        available = clear + 2;
        oldCode = NULL_CODE;
        codeSize = dataSize + 1;
        codeMask = (1 << codeSize) - 1;
        for (code = 0; code < clear; code++) {
            // XXX ArrayIndexOutOfBoundsException.
            prefix[code] = 0;
            suffix[code] = (byte) code;
        }

        // Decode GIF pixel stream.
        datum = bits = count = first = top = pi = bi = 0;
        for (i = 0; i < npix; ) {
            // Load bytes until there are enough bits for a code.
            if (count == 0) {
                // Read a new data block.
                count = readBlock();
                if (count <= 0) {
                    status = STATUS_PARTIAL_DECODE;
                    break;
                }
                bi = 0;
            }

            datum += (((int) block[bi]) & 0xff) << bits;
            bits += 8;
            bi++;
            count--;

            while (bits >= codeSize) {
                // Get the next code.
                code = datum & codeMask;
                datum >>= codeSize;
                bits -= codeSize;

                // Interpret the code.
                if (code == clear) {
                    // Reset decoder.
                    codeSize = dataSize + 1;
                    codeMask = (1 << codeSize) - 1;
                    available = clear + 2;
                    oldCode = NULL_CODE;
                    continue;
                }

                if (code > available) {
                    status = STATUS_PARTIAL_DECODE;
                    break;
                }

                if (code == endOfInformation) {
                    break;
                }

                if (oldCode == NULL_CODE) {
                    pixelStack[top++] = suffix[code];
                    oldCode = code;
                    first = code;
                    continue;
                }
                inCode = code;
                if (code >= available) {
                    pixelStack[top++] = (byte) first;
                    code = oldCode;
                }
                while (code >= clear) {
                    pixelStack[top++] = suffix[code];
                    code = prefix[code];
                }
                first = ((int) suffix[code]) & 0xff;
                pixelStack[top++] = (byte) first;

                // Add a new string to the string table.
                if (available < MAX_STACK_SIZE) {
                    prefix[available] = (short) oldCode;
                    suffix[available] = (byte) first;
                    available++;
                    if (((available & codeMask) == 0) && (available < MAX_STACK_SIZE)) {
                        codeSize++;
                        codeMask += available;
                    }
                }
                oldCode = inCode;

                while (top > 0) {
                    // Pop a pixel off the pixel stack.
                    mainPixels[pi++] = pixelStack[--top];
                    i++;
                }
            }
        }

        // Clear missing pixels.
        for (i = pi; i < npix; i++) {
            mainPixels[i] = 0;
        }
    }
513509
function bytesToSize (bytes) {
  const sizes = ['bytes', 'kb', 'mb', 'gb', 'tb']
  if (bytes === 0) return '0 byte'
  const i = parseInt(Math.floor(Math.log(bytes) / Math.log(BYTES)))
  return (bytes / Math.pow(BYTES, i)).toFixed(DISPLAY_DECIMALS) + sizes[i]
}
235103
def to_bytes(s, encoding=None, errors='strict'):
    """"""
    encoding = encoding or 'utf-8'

    if is_unicode(s):
        return s.encode(encoding, errors)
    elif is_strlike(s):
        return s
    else:
        if six.PY2:
            return str(s)
        else:
            return str(s).encode(encoding, errors)
829481
def processGif(searchStr):
    '''
    
    '''
    
    # Sanitizing searchStr
    # TODO: Find a better way to do this
    searchStr.replace('| ', ' ')
    searchStr.replace('|', ' ')
    searchStr.replace(', ', ' ')
    searchStr.replace(',', ' ')
    searchStr.rstrip()
    searchStr = searchStr.strip('./?\'!,')
    searchStr = searchStr.replace(' ', '+')

    if searchStr is None or searchStr == '':
        print("No search parameters specified!")
        return no_search_params

    api_url = 'http://api.giphy.com/v1/gifs/search'
    api_key = 'dc6zaTOxFJmzC'

    payload = {
        'q': searchStr,
        'limit': 1,
        'api_key': api_key,
    }

    r = requests.get(api_url, params=payload)
    parsed_json = json.loads(r.text)
    # print(parsed_json)

    if len(parsed_json['data']) == 0:
        print("Couldn't find suitable match for gif! :(")
        return -1

    else:               # Success!
        imgURL = parsed_json['data'][0]['images']['fixed_height']['url']
        # print(imgURL)
        return imgURL