// previewGIF handles resizing multiple frames in an animated gif.
// Based on code in https://github.com/dpup/go-scratch/blob/master/gif-resize/gif-resize.go
350078
func previewGIF(ctx context.Context, log utils.DebugLabeler, src io.Reader, basename string) (*PreviewRes, error) {
	raw, err := ioutil.ReadAll(src)
	if err != nil {
		return nil, err
	}
	g, err := gif.DecodeAll(bytes.NewReader(raw))
	if err != nil {
		return nil, err
	}

	frames := len(g.Image)
	if frames == 0 {
		return nil, errors.New("no image frames in GIF")
	}

	log.Debug(ctx, "previewGIF: number of frames = %d", frames)

	var baseDuration int
	if frames > 1 {
		if len(raw) < 10*1024*1024 {
			log.Debug(ctx, "previewGif: not resizing because multiple-frame original < 10MB")

			// don't resize if multiple frames and < 5MB
			bounds := g.Image[0].Bounds()
			duration := gifDuration(g)
			res := &PreviewRes{
				Source:            raw,
				ContentType:       "image/gif",
				BaseWidth:         bounds.Dx(),
				BaseHeight:        bounds.Dy(),
				PreviewWidth:      bounds.Dx(),
				PreviewHeight:     bounds.Dy(),
				BaseDurationMs:    duration,
				PreviewDurationMs: duration,
			}
			return res, nil
		}

		log.Debug(ctx, "previewGif: large multiple-frame gif: %d, just using frame 0", len(raw))
		baseDuration = gifDuration(g)
		g.Image = g.Image[:1]
		g.Delay = g.Delay[:1]
		g.Disposal = g.Disposal[:1]
	}

	// create a new image based on the first frame to draw
	// the incremental frames
	origBounds := g.Image[0].Bounds()
	img := image.NewRGBA(origBounds)

	// draw each frame, then resize it, replacing the existing frames.
	width, height := previewDimensions(origBounds)
	log.Debug(ctx, "previewGif: resizing to %d x %d", width, height)
	for index, frame := range g.Image {
		bounds := frame.Bounds()
		draw.Draw(img, bounds, frame, bounds.Min, draw.Over)
		g.Image[index] = imageToPaletted(resize.Resize(width, height, img, resize.Bicubic))
		log.Debug(ctx, "previewGIF: resized frame %d", index)
	}

	// change the image Config to the new size
	g.Config.Width = int(width)
	g.Config.Height = int(height)

	// encode all the frames into buf
	var buf bytes.Buffer
	if err := gif.EncodeAll(&buf, g); err != nil {
		return nil, err
	}

	res := &PreviewRes{
		Source:         buf.Bytes(),
		ContentType:    "image/gif",
		BaseWidth:      origBounds.Dx(),
		BaseHeight:     origBounds.Dy(),
		PreviewWidth:   int(width),
		PreviewHeight:  int(height),
		BaseDurationMs: baseDuration,
	}

	if len(g.Image) > 1 {
		res.PreviewDurationMs = gifDuration(g)
	}

	return res, nil
}
1179976
func (c oauthClient) FilePreview(
	fileID uint,
	platform string,
	size string,
) (wl.FilePreview, error) {
	if fileID == 0 {
		return wl.FilePreview{}, errors.New("fileID must be > 0")
	}

	url := fmt.Sprintf(
		"%s/previews?file_id=%d",
		c.apiURL,
		fileID,
	)

	if platform != "" {
		url = fmt.Sprintf(
			"%s&platform=%s",
			url,
			platform,
		)
	}

	if size != "" {
		url = fmt.Sprintf(
			"%s&size=%s",
			url,
			size,
		)
	}

	req, err := c.newGetRequest(url)
	if err != nil {
		return wl.FilePreview{}, err
	}

	resp, err := c.do(req)
	if err != nil {
		return wl.FilePreview{}, err
	}

	if resp.StatusCode != http.StatusOK {
		return wl.FilePreview{}, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusOK)
	}

	task := wl.FilePreview{}
	err = json.NewDecoder(resp.Body).Decode(&task)
	if err != nil {
		return wl.FilePreview{}, err
	}
	return task, nil
}
430294
func (image *Image) Resize(param *ResizeParam) *Image {
	return image.setActionParam(ResizeOperation, param)
}
310218
func (msg *Message) Resize(newSize int64) error {
	if newSize > maxAllowedBufferSize || newSize < 0 {
		return fmt.Errorf("Requested new buffer size is invalid. Requested: %d, allowed: 0..%d", newSize, maxAllowedBufferSize)
	}
	if int64(len(msg.Data)) == newSize {
		return nil
	}
	msg.Data = make([]byte, newSize)
	return nil
}
868577
func Colorizef(c Color, b BackgroundColor, format string, args ...interface{}) string {
	args = append([]interface{}{ResetColors, c, b}, args...)
	args = append(args, ResetColors)
	return fmt.Sprintf("%s%s%s"+format+"%s", args...)
}
1298717
func RandomImageSize(size int, data []byte) (image.Image, error) {
	randExtent := len(palette.WebSafe) - 32
	rand.Seed(time.Now().UnixNano())
	colorIndex := rand.Intn(randExtent)
	backColorIndex := colorIndex - 1
	if backColorIndex < 0 {
		backColorIndex = randExtent - 1
	}

	// Define size, background, and forecolor
	imgMaker, err := identicon.New(size,
		palette.WebSafe[backColorIndex], palette.WebSafe[colorIndex:colorIndex+32]...)
	if err != nil {
		return nil, fmt.Errorf("identicon.New: %v", err)
	}
	return imgMaker.Make(data), nil
}
607367
func (v GifmsResource) Show(c buffalo.Context) error {
	// Get the DB connection from the context
	tx, ok := c.Value("tx").(*pop.Connection)
	if !ok {
		return errors.WithStack(errors.New("no transaction found"))
	}

	// Allocate an empty Gifm
	gifm := &models.Gifm{}

	// To find the Gifm the parameter gifm_id is used.
	if err := tx.Find(gifm, c.Param("gifm_id")); err != nil {
		return c.Error(404, err)
	}

	return c.Render(200, r.Auto(c, gifm))
}
11955
func (d *Context) ResizeBuffer(index int, newSize int) unsafe.Pointer {
	return C.duk_resize_buffer(d.duk_context, C.duk_idx_t(index), C.duk_size_t(newSize))
}
757392
func (c *Client) GetGifById(id string) (*Gif, error) {

	// construct and execute the HTTP request
	u := fmt.Sprintf("gifs/%s", id)
	sr := &singleResult{}
	if err := c.makeRequest(u, &url.Values{}, sr); err != nil {
		return nil, err
	}

	return sr.Data, nil
}
142953
func (w *Window) SetFramebufferSizeCallback(cbfun FramebufferSizeCallback) (previous FramebufferSizeCallback) {
	previous = w.fFramebufferSizeHolder
	w.fFramebufferSizeHolder = cbfun
	if cbfun == nil {
		C.glfwSetFramebufferSizeCallback(w.data, nil)
	} else {
		C.glfwSetFramebufferSizeCallbackCB(w.data)
	}
	panicError()
	return previous
}
570125
func (c *Client) GetGifsById(ids ...string) ([]*Gif, error) {

	// check that a query string was actually passed in
	if len(ids) > 100 {
		err := errors.New("Cannot fetch more than 100 GIFs at a time.")
		return nil, err
	}

	// build query string that will be appended to url
	qs := &url.Values{}
	qs.Set("ids", strings.Join(ids, ","))

	// construct and execute the HTTP request
	pr := &paginatedResults{}
	if err := c.makeRequest("gifs", qs, pr); err != nil {
		return nil, err
	}

	return pr.Data, nil
}
534413
func resize(bs []byte, size int) []byte {
	if cap(bs) < size {
		return make([]byte, size)
	}
	return bs[:size]
}
279909
func (w *Window) SetFramebufferSizeCallback(cbfun func(w *Window, width int, height int)) {
	if cbfun == nil {
		C.glfwSetFramebufferSizeCallback(w.data, nil)
	} else {
		w.fFramebufferSizeHolder = cbfun
		C.glfwSetFramebufferSizeCallbackCB(w.data)
	}
}
136994
func (i *ImageService) imageIsDangling(imgID image.ID) bool {
	return !(len(i.referenceStore.References(imgID.Digest())) > 0 || len(i.imageStore.Children(imgID)) > 0)
}
944679
func Paste(background, img image.Image, pos image.Point) *image.NRGBA {
	dst := Clone(background)
	pos = pos.Sub(background.Bounds().Min)
	pasteRect := image.Rectangle{Min: pos, Max: pos.Add(img.Bounds().Size())}
	interRect := pasteRect.Intersect(dst.Bounds())
	if interRect.Empty() {
		return dst
	}
	src := newScanner(img)
	parallel(interRect.Min.Y, interRect.Max.Y, func(ys <-chan int) {
		for y := range ys {
			x1 := interRect.Min.X - pasteRect.Min.X
			x2 := interRect.Max.X - pasteRect.Min.X
			y1 := y - pasteRect.Min.Y
			y2 := y1 + 1
			i1 := y*dst.Stride + interRect.Min.X*4
			i2 := i1 + interRect.Dx()*4
			src.scan(x1, y1, x2, y2, dst.Pix[i1:i2])
		}
	})
	return dst
}
918497
func onResize(window *glfw.Window, w, h int) {
	w, h = window.GetSize() // query window to get screen pixels
	width, height := window.GetFramebufferSize()
	gl.Viewport(0, 0, int32(width), int32(height))
	gl.MatrixMode(gl.PROJECTION)
	gl.LoadIdentity()
	gl.Ortho(0, float64(w), 0, float64(h), -1, 1)
	gl.MatrixMode(gl.MODELVIEW)
	gl.LoadIdentity()
	gl.ClearColor(1, 1, 1, 1)
}
1212615
func decodeRGB(dinfo *C.struct_jpeg_decompress_struct) (dest *rgb.Image, err error) {
	C.jpeg_calc_output_dimensions(dinfo)
	dest = rgb.NewImage(image.Rect(0, 0, int(dinfo.output_width), int(dinfo.output_height)))

	dinfo.out_color_space = C.JCS_RGB
	readScanLines(dinfo, dest.Pix, dest.Stride)
	return
}