Exemplo n.º 1
0
// Sets skin.Processed to an isometric render of the head from a top-left angle (showing 3 sides).
func (skin *mcSkin) GetCube(width int) error {
	// Crop out the top of the head
	topFlat := imaging.Crop(skin.Image, image.Rect(8, 0, 16, 8))
	// Resize appropriately, so that it fills the `width` when rotated 45 def.
	topFlat = imaging.Resize(topFlat, int(float64(width)*math.Sqrt(2)/3+1), 0, imaging.NearestNeighbor)
	// Create the Gift filter
	filter := gift.New(
		gift.Rotate(45, color.Transparent, gift.LinearInterpolation),
	)
	bounds := filter.Bounds(topFlat.Bounds())
	top := image.NewNRGBA(bounds)
	// Draw it on the filter, then smush it!
	filter.Draw(top, topFlat)
	top = imaging.Resize(top, width+2, width/3, imaging.NearestNeighbor)
	// Skew the front and sides at 15 degree angles to match up with the
	// head that has been smushed
	front := skin.cropHead(skin.Image).(*image.NRGBA)
	side := imaging.Crop(skin.Image, image.Rect(0, 8, 8, 16))
	front = imaging.Resize(front, width/2, int(float64(width)/1.75), imaging.NearestNeighbor)
	side = imaging.Resize(side, width/2, int(float64(width)/1.75), imaging.NearestNeighbor)
	front = skewVertical(front, math.Pi/12)
	side = skewVertical(imaging.FlipH(side), math.Pi/-12)

	// Create a new image to assemble upon
	skin.Processed = image.NewNRGBA(image.Rect(0, 0, width, width))
	// Draw each side
	draw.Draw(skin.Processed.(draw.Image), image.Rect(0, width/6, width/2, width), side, image.Pt(0, 0), draw.Src)
	draw.Draw(skin.Processed.(draw.Image), image.Rect(width/2, width/6, width, width), front, image.Pt(0, 0), draw.Src)
	// Draw the top we created
	draw.Draw(skin.Processed.(draw.Image), image.Rect(-1, 0, width+1, width/3), top, image.Pt(0, 0), draw.Over)

	return nil
}
Exemplo n.º 2
0
// transformImage modifies the image m based on the transformations specified
// in opt.
func transformImage(m image.Image, opt Options) image.Image {
	// resize if needed
	if w, h, resize := resizeParams(m, opt); resize {
		if opt.Fit {
			m = imaging.Fit(m, w, h, resampleFilter)
		} else {
			if w == 0 || h == 0 {
				m = imaging.Resize(m, w, h, resampleFilter)
			} else {
				m = imaging.Resize(m, w, h, imaging.Lanczos)
			}
		}
	}

	// flip
	if opt.FlipVertical {
		m = imaging.FlipV(m)
	}
	if opt.FlipHorizontal {
		m = imaging.FlipH(m)
	}

	// rotate
	switch opt.Rotate {
	case 90:
		m = imaging.Rotate90(m)
	case 180:
		m = imaging.Rotate180(m)
	case 270:
		m = imaging.Rotate270(m)
	}

	return m
}
Exemplo n.º 3
0
func generateThumbnailImage(img image.Image, thumbnailPath string, width int, height int) {
	thumbWidth := float64(utils.Cfg.FileSettings.ThumbnailWidth)
	thumbHeight := float64(utils.Cfg.FileSettings.ThumbnailHeight)
	imgWidth := float64(width)
	imgHeight := float64(height)

	var thumbnail image.Image
	if imgHeight < thumbHeight && imgWidth < thumbWidth {
		thumbnail = img
	} else if imgHeight/imgWidth < thumbHeight/thumbWidth {
		thumbnail = imaging.Resize(img, 0, utils.Cfg.FileSettings.ThumbnailHeight, imaging.Lanczos)
	} else {
		thumbnail = imaging.Resize(img, utils.Cfg.FileSettings.ThumbnailWidth, 0, imaging.Lanczos)
	}

	buf := new(bytes.Buffer)
	if err := jpeg.Encode(buf, thumbnail, &jpeg.Options{Quality: 90}); err != nil {
		l4g.Error(utils.T("api.file.handle_images_forget.encode_jpeg.error"), thumbnailPath, err)
		return
	}

	if err := WriteFile(buf.Bytes(), thumbnailPath); err != nil {
		l4g.Error(utils.T("api.file.handle_images_forget.upload_thumb.error"), thumbnailPath, err)
		return
	}
}
Exemplo n.º 4
0
// Extracts thumbnail
func (c *Convertor) ExtractThumbnail(file string, info os.FileInfo) {
	c.CurrFile += 1

	cover, err := c.GetCoverImage(file, info)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error GetCoverImage: %v\n", err.Error())
		return
	}

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error Thumbnail: %v\n", err.Error())
		return
	}

	if c.Opts.Width > 0 || c.Opts.Height > 0 {
		if c.Opts.Fit {
			cover = imaging.Fit(cover, c.Opts.Width, c.Opts.Height, filters[c.Opts.Filter])
		} else {
			cover = imaging.Resize(cover, c.Opts.Width, c.Opts.Height, filters[c.Opts.Filter])
		}
	} else {
		cover = imaging.Resize(cover, 256, 0, filters[c.Opts.Filter])
	}

	imagick.Initialize()

	mw := imagick.NewMagickWand()
	defer mw.Destroy()

	b := new(bytes.Buffer)
	png.Encode(b, cover)

	err = mw.ReadImageBlob(b.Bytes())
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error ReadImageBlob: %v\n", err.Error())
	}

	var fileuri string
	var filename string

	if c.Opts.Outfile == "" {
		fileuri = "file://" + file
		filename = filepath.Join(c.Opts.Outdir, fmt.Sprintf("%x.png", md5.Sum([]byte(fileuri))))
	} else {
		abs, _ := filepath.Abs(c.Opts.Outfile)
		fileuri = "file://" + abs
		filename = abs
	}

	mw.SetImageFormat("PNG")
	mw.SetImageProperty("Software", "CBconvert")
	mw.SetImageProperty("Description", "Thumbnail of "+fileuri)
	mw.SetImageProperty("Thumb::URI", fileuri)
	mw.SetImageProperty("Thumb::MTime", strconv.FormatInt(info.ModTime().Unix(), 10))
	mw.SetImageProperty("Thumb::Size", strconv.FormatInt(info.Size(), 10))
	mw.SetImageProperty("Thumb::Mimetype", mime.TypeByExtension(filepath.Ext(file)))

	mw.WriteImage(filename)
}
Exemplo n.º 5
0
// Extracts cover
func (c *Convertor) ExtractCover(file string, info os.FileInfo) {
	c.CurrFile += 1

	cover, err := c.GetCoverImage(file, info)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error GetCoverImage: %v\n", err.Error())
		return
	}

	if c.Opts.Width > 0 || c.Opts.Height > 0 {
		if c.Opts.Fit {
			cover = imaging.Fit(cover, c.Opts.Width, c.Opts.Height, filters[c.Opts.Filter])
		} else {
			cover = imaging.Resize(cover, c.Opts.Width, c.Opts.Height, filters[c.Opts.Filter])
		}
	}

	filename := filepath.Join(c.Opts.Outdir, fmt.Sprintf("%s.jpg", c.getBasename(file)))
	f, err := os.Create(filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error Create: %v\n", err.Error())
		return
	}
	defer f.Close()

	jpeg.Encode(f, cover, &jpeg.Options{c.Opts.Quality})
}
Exemplo n.º 6
0
func ResizeHandler(w http.ResponseWriter, r *http.Request) {
	// parse url vars
	v := mux.Vars(r)
	width, _ := v["width"]
	height, _ := v["height"]
	x, _ := strconv.Atoi(width)
	y, _ := strconv.Atoi(height)

	imageUrl, _ := v["imageUrl"]
	m := getImg(imageUrl)

	cropBox, _ := getFillCrop(m, float32(x)/float32(y))
	cropRect := image.Rect(cropBox.X, cropBox.Y, cropBox.X+cropBox.Width, cropBox.Y+cropBox.Height)
	croppedImg := imaging.Crop(m, cropRect)

	// convert to opencv image
	//srcImage := opencv.FromImage(m)
	//if srcImage == nil {
	//  fmt.Printf("Couldn't create opencv Image")
	//}
	//defer srcImage.Release()
	//croppedImage := opencv.Crop(srcImage, cropBox.X, cropBox.Y, cropBox.Width, cropBox.Height)
	//resizedImage := opencv.Resize(croppedImage, x, y, opencv.CV_INTER_LINEAR)
	resizedImage := imaging.Resize(croppedImg, x, y, imaging.CatmullRom)
	jpeg.Encode(w, resizedImage, &jpeg.Options{Quality: 90})
}
Exemplo n.º 7
0
func decodeFunc(h []string) func(rec []string) (draw.Image, error) {
	if h[0] == "ImageId" {
		return decodePGM
	}
	if h[0] == "left_eye_center_x" {
		return func(rec []string) (draw.Image, error) {
			src, err := decodePGM(rec)
			if err != nil {
				return nil, err
			}
			b := src.Bounds()
			img := image.NewRGBA(b)
			draw.Draw(img, b, src, b.Min, draw.Src)
			for i := 0; i < len(rec)/2; i++ {
				/*                x, err := strconv.ParseFloat(rec[2*i], 64)
				                  if err != nil {
				                      log.Print(err)
				                      continue
				                  }
				                  y, err := strconv.ParseFloat(rec[2*i + 1], 64)
				                  if err != nil {
				                      log.Print(err)
				                      continue
				                  }
				                  img.Set(int(x + 0.5), int(y + 0.5), color.RGBA{0xff, 0, 0, 0xff})*/
			}
			// overlayPoints(
			i := imaging.Resize(img, 500, 0, imaging.Lanczos)
			return i, nil
		}
	}
	return nil
}
Exemplo n.º 8
0
func Resized(ext string, data []byte, width, height int) (resized []byte, w int, h int) {
	if width == 0 && height == 0 {
		return data, 0, 0
	}
	srcImage, _, err := image.Decode(bytes.NewReader(data))
	if err == nil {
		bounds := srcImage.Bounds()
		var dstImage *image.NRGBA
		if bounds.Dx() > width && width != 0 || bounds.Dy() > height && height != 0 {
			if width == height && bounds.Dx() != bounds.Dy() {
				dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos)
				w, h = width, height
			} else {
				dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos)
			}
		} else {
			return data, bounds.Dx(), bounds.Dy()
		}
		var buf bytes.Buffer
		switch ext {
		case ".png":
			png.Encode(&buf, dstImage)
		case ".jpg", ".jpeg":
			jpeg.Encode(&buf, dstImage, nil)
		case ".gif":
			gif.Encode(&buf, dstImage, nil)
		}
		return buf.Bytes(), dstImage.Bounds().Dx(), dstImage.Bounds().Dy()
	} else {
		glog.Error(err)
	}
	return data, 0, 0
}
Exemplo n.º 9
0
func (api *Api) Resize(imgloc string, xsize, ysize int, resizeType string) bool {
	dest := setSize(imgloc, xsize, ysize)
	if _, err := os.Stat(dest); err == nil {
		return true
	}
	bts, err := ioutil.ReadFile(imgloc)
	if err != nil {
		fmt.Println(err)
		return false
	}
	rdr := bytes.NewReader(bts)
	i, _, err := image.Decode(rdr)
	if err != nil {
		fmt.Println(err)
		return false
	}
	var fsimg *image.NRGBA
	switch resizeType {
	case "fit":
		fsimg = imaging.Fit(i, xsize, ysize, imaging.Lanczos)
	case "thumb":
		fsimg = imaging.Thumbnail(i, xsize, ysize, imaging.Lanczos)
	default:
		fsimg = imaging.Resize(i, xsize, ysize, imaging.Lanczos)
	}
	out, err := os.Create(dest)
	if err != nil {
		return false
	}
	defer out.Close()
	jpeg.Encode(out, fsimg, nil)
	return true
}
Exemplo n.º 10
0
func CenterCrop(img *io.Reader, width, height int) ([]byte, error) {
	m, _, err := image.Decode(*img)
	if err != nil {
		return nil, err
	}

	// TODO: I probably can switch to using imaging.Thumbnail here.
	imgW := float64(m.Bounds().Max.X - m.Bounds().Min.X)
	imgH := float64(m.Bounds().Max.Y - m.Bounds().Min.Y)
	targetW := float64(width)
	targetH := float64(height)

	var scale float64

	if imgW*targetH > targetW*imgH {
		scale = targetH / imgH
	} else {
		scale = targetW / imgW
	}

	m = imaging.Resize(m, int(imgW*scale), int(imgH*scale), imaging.Lanczos)
	m = imaging.CropCenter(m, width, height)

	buf := new(bytes.Buffer)
	jpeg.Encode(buf, m, &jpeg.Options{Quality: 95})

	return buf.Bytes(), nil
}
Exemplo n.º 11
0
func (image *Image) resizePreview(errorChan chan error, srcImage image.Image) {
	size := srcImage.Bounds().Size()
	ratio := float64(size.Y) / float64(size.X)
	targetHeight := int(float64(widthPreview) * ratio)

	dstImage := imaging.Resize(srcImage, widthPreview, targetHeight, imaging.Lanczos)
	dest := "./data/images/preview/" + image.Location
	errorChan <- imaging.Save(dstImage, dest)
}
Exemplo n.º 12
0
func resizeImage(filename string, size int) string {
	resizedFile := filename + ".resized.png"
	img, err := imaging.Open(filename)
	if err != nil {
		panic(err)
	}
	dstimg := imaging.Resize(img, size, 0, imaging.Box)
	imaging.Save(dstimg, resizedFile)
	return resizedFile
}
Exemplo n.º 13
0
/* resize when there is no height constraint, otherwise crop */
func (result *imageInfo) resizeOrCrop(img image.Image, width int, height int) image.Image {
	var imgdata image.Image
	if height == 0 {
		imgdata = imaging.Resize(img, width, height, imaging.Lanczos)
	} else {
		imgdata = imaging.CropCenter(img, width, height)
	}
	result.width = imgdata.Bounds().Max.X
	result.height = imgdata.Bounds().Max.Y
	return imgdata
}
Exemplo n.º 14
0
func (be *Backend) GenerateThumbnail(bin string, filename string, width int, height int, crop bool) error {
	f, err := be.GetFileMetaData(bin, filename)
	if err != nil {
		return err
	}

	if strings.Split(f.MIME, "/")[0] != "image" {
		return errors.New("Batch job skipped: " + filename + " is not an image")
	}

	fpath := filepath.Join(be.filedir, bin, filename)
	cachedir := filepath.Join(be.filedir, bin, ".cache")
	if !isDir(cachedir) {
		if err := os.Mkdir(cachedir, 0700); err != nil {
			return err
		}
	}
	dst := filepath.Join(cachedir, strconv.Itoa(width)+"x"+strconv.Itoa(height)+"-"+filename)

	// Optimize to skip thumbnail generation if the thumbnail file exists
	// and is newer than the file.
	fi, err := os.Lstat(dst)
	if err == nil {
		if f.CreatedAt.After(fi.ModTime()) {
			// File newer than thumbnail. Ok to generate.
		} else {
			// File older than thumbnail. No need to generate.
			return nil
		}
	}

	s, err := imaging.Open(fpath)
	if err != nil {
		return err
	}

	if crop {
		im := imaging.Fill(s, width, height, imaging.Center, imaging.Lanczos)
		err = imaging.Save(im, dst)
	} else {
		im := imaging.Resize(s, width, height, imaging.Lanczos)
		err = imaging.Save(im, dst)
	}

	f.Links = be.GenerateLinks(f.Bin, f.Filename)
	be.Lock()
	defer be.Unlock()
	id := bin + filename
	delete(be.files, id)
	be.files[id] = f

	return err
}
Exemplo n.º 15
0
func normalizeInput(input image.Image, maxSize int) (image.Image, float64, error) {
	var scale float64
	if input.Bounds().Dx() > maxSize {
		scale = float64(input.Bounds().Dx()) / float64(maxSize)
	} else {
		scale = float64(input.Bounds().Dy()) / float64(maxSize)
	}

	log.Printf("Normalizing to %dx%d\n", int(float64(input.Bounds().Dx())/scale), int(float64(input.Bounds().Dy())/scale))
	resized := imaging.Resize(input, int(float64(input.Bounds().Dx())/scale), int(float64(input.Bounds().Dy())/scale), imaging.Lanczos)

	return resized, scale, nil
}
Exemplo n.º 16
0
func MakeFromImage(srcImage image.Image, t string, w, h int) (image *image.NRGBA, err error) {
	switch t {
	case "thumbnail":
		image = imaging.Thumbnail(srcImage, w, h, imaging.Lanczos)
	case "resize":
		image = imaging.Resize(srcImage, w, h, imaging.Lanczos)
	case "fit":
		image = imaging.Fit(srcImage, w, h, imaging.Lanczos)
	default:
		image = imaging.Thumbnail(srcImage, w, h, imaging.Lanczos)
	}

	return image, nil
}
Exemplo n.º 17
0
func thumbs(args []string, thumbSizes []int) {
	if newThumbsSizes != "" {
		vals := strings.Split(newThumbsSizes, ",")
		thumbSizes = make([]int, len(vals))
		for i := 0; i < len(vals); i++ {
			numstr := strings.TrimSpace(vals[i])
			if numstr == "" {
				thumbSizes[i] = 0
				continue
			}
			num, err := strconv.Atoi(numstr)
			if err != nil {
				log.Print(err)
				continue
			}
			thumbSizes[i] = num
		}
	}

	for i := 0; i < len(args); i++ {

		file := args[i]
		ext := filepath.Ext(file)

		_, err := os.Stat(file)
		if err != nil {
			log.Fatal("file " + file + " is not accessible")
		}

		img, err := imaging.Open(file)
		if err != nil {
			log.Fatal(err)
		}

		for j := 0; j < len(thumbSizes); j++ {
			if thumbSizes[j] == 0 {
				continue
			}
			resized := imaging.Resize(img, thumbSizes[j], 0, imaging.Lanczos)
			rect := resized.Bounds().Max
			out := fmt.Sprintf("%s_%dx%d%s",
				strings.TrimSuffix(file, ext), rect.X, rect.Y, ext)
			err = imaging.Save(resized, out)
			log.Println("saved " + out)
			if err != nil {
				log.Fatal(err)
			}
		}
	}
}
Exemplo n.º 18
0
func Resize(src io.Reader, c *CacheContext) (io.Reader, error) {
	raw, err := ioutil.ReadAll(src)
	if err != nil {
		return nil, err
	}

	width := c.Width
	data := bytes.NewReader(raw)
	img, format, err := image.Decode(data)
	if err != nil {
		return nil, err
	}
	var resizedImage image.NRGBA
	if c.Crop {

		minDimension := int(math.Min(float64(img.Bounds().Size().X), float64(img.Bounds().Size().Y)))

		if minDimension < c.Width || c.Width == 0 {
			width = minDimension
		}

		resizedImage = *imaging.Fill(img, width, width, imaging.Center, imaging.Lanczos)
	} else {
		resizedImage = *imaging.Resize(img, width, 0, imaging.Lanczos)
	}

	buf := new(bytes.Buffer)
	var imgFormat imaging.Format
	switch format {
	case "png":
		imgFormat = imaging.PNG
	case "jpeg":
		imgFormat = imaging.JPEG
	case "tiff":
		imgFormat = imaging.TIFF
	case "bmp":
		imgFormat = imaging.BMP
	default:
		return nil, errors.New("unsupported image format")
	}

	err = imaging.Encode(buf, resizedImage.SubImage(resizedImage.Rect), imgFormat)
	if err != nil {
		return nil, err
	}

	return buf, err

}
Exemplo n.º 19
0
func fitCropScale(i image.Image, r image.Rectangle) image.Image {
	wantRatio := float64(r.Bounds().Dx()) / float64(r.Bounds().Dy())
	haveRatio := float64(i.Bounds().Dx()) / float64(i.Bounds().Dy())

	sliceRect := image.Rectangle{}

	if haveRatio > wantRatio {
		wantwidth := wantRatio * float64(i.Bounds().Dy())
		sliceRect = image.Rect(i.Bounds().Dx()/2-int(wantwidth/2), 0, i.Bounds().Dx()/2+int(wantwidth/2), i.Bounds().Dy())
	} else {
		wantheight := float64(i.Bounds().Dx()) / wantRatio
		sliceRect = image.Rect(0, i.Bounds().Dy()/2-int(wantheight/2), i.Bounds().Dx(), i.Bounds().Dy()/2+int(wantheight/2))
	}

	return imaging.Resize(imaging.Crop(i, sliceRect), r.Dx(), r.Dy(), imaging.Lanczos)
}
Exemplo n.º 20
0
func (h *ImgHandler) handlePOST(w http.ResponseWriter, req *http.Request) {
	s := MgoSession.Copy()
	defer s.Close()

	name, path := h.convertPath(req.URL.Path)
	document, _ := new(Document).Find(s, name, path)
	document.Name = name
	document.Path = path

	origin, format, err := image.Decode(req.Body)
	if err != nil {
		log.Panicln(err)
		io.WriteString(w, err.Error())
		return
	}

	// image is larger than the specified stored size, we need to resize it
	var img image.Image
	if (Configuration.StoredSize.Width > 0 && origin.Bounds().Dx() > Configuration.StoredSize.Width) ||
		(Configuration.StoredSize.Height > 0 && origin.Bounds().Dy() > Configuration.StoredSize.Height) {
		img = imaging.Resize(origin, Configuration.StoredSize.Width, Configuration.StoredSize.Height, imaging.CatmullRom)
	} else {
		img = origin
	}

	buf := new(bytes.Buffer)
	err = h.writeImage(buf, img, format)
	if err != nil {
		log.Panicln(err)
		io.WriteString(w, err.Error())
		return
	}
	document.Binary = buf.Bytes()

	contentType := req.Header.Get("Content-Type")
	if contentType != "" {
		document.ContentType = contentType
	}

	err = document.Save(s)
	if err != nil {
		log.Panicln(err)
		io.WriteString(w, err.Error())
	} else {
		io.WriteString(w, "stored\n")
	}
}
Exemplo n.º 21
0
// GetHash returns a phash string for a JPEG image
func GetHash(reader io.Reader) (string, error) {
	image, err := imaging.Decode(reader)

	if err != nil {
		return "", err
	}

	image = imaging.Resize(image, 32, 32, imaging.Lanczos)
	image = imaging.Grayscale(image)

	imageMatrixData := getImageMatrix(image)
	dctMatrix := getDCTMatrix(imageMatrixData)

	smallDctMatrix := reduceMatrix(dctMatrix, 8)
	dctMeanValue := calculateMeanValue(smallDctMatrix)
	return buildHash(smallDctMatrix, dctMeanValue), nil
}
Exemplo n.º 22
0
//缩放
func (this *Image) resize(filename string, w, h, s int) (string, error) {
	if this.source == nil {
		if err := this.open(filename); err != nil {
			return "", err
		}
	}

	var dst *image.NRGBA
	dst = imaging.Resize(this.source, w, h, imaging.CatmullRom)
	//取目标文件名
	dstfile, err := this.dstFilename(s)
	if err != nil {
		return "", err
	}
	//保存文件
	return dstfile, imaging.Save(dst, dstfile)
}
Exemplo n.º 23
0
//Resize with mode plain. Does the acutal resizing and returns the image
//errors only if dstWidth or dstHeight is invalid
func (p PlainResizer) Resize(input image.Image, dstWidth, dstHeight int) (image.Image, error) {
	if dstWidth < 0 && dstHeight < 0 {
		return nil, fmt.Errorf("Either width or height must be greater zero to keep the existing ratio")
	}

	//since we use -1 as optional and imaging uses zero as optional
	//we change -1 to 0 to keep the aspect ratio
	if dstWidth < 0 {
		dstWidth = 0
	}

	if dstHeight < 0 {
		dstHeight = 0
	}

	return imaging.Resize(input, dstWidth, dstHeight, imaging.Lanczos), nil
}
Exemplo n.º 24
0
func Benchmark(img image.Image, rounds int, targets ...Size) (results Results) {
	var (
		t  time.Time
		Δt time.Duration
	)
	results = make(map[string]map[Size]Result)

	for name, filter := range filters {
		results[name] = make(map[Size]Result)
		for _, target := range targets {
			var (
				r     Result // The result for this filter and size.
				total time.Duration
			)
			for i := 0; i < rounds; i++ {
				// Take resizing time
			resize:
				t = time.Now()
				imaging.Resize(img, target[0], target[1], filter)
				Δt = time.Since(t)
				// FIXME:
				// For some reason NearestNeighbor sometimes gets zero duration.
				// If this happens, we'll just try again, I guess.
				if Δt == 0 {
					goto resize
				}

				// Set min & max if need be.
				if r.Min == 0 || Δt < r.Min {
					r.Min = Δt
				}
				if Δt > r.Max {
					r.Max = Δt
				}
				// Accumulate total time.
				total += Δt
			}
			// Calculate average resize time.
			r.Avg = total / time.Duration(rounds)
			// Append to the results
			results[name][target] = r
		}
	}

	return
}
Exemplo n.º 25
0
func ResampleImage(src image.Image, w int, h int) (image.Image, error) {
	sw := src.Bounds().Dx()
	sh := src.Bounds().Dy()
	sr := float32(sw) / float32(sh)

	if w > sw {
		w = sw
	}

	if h > sh {
		h = sh
	}

	if w == 0 && h == 0 {
		return src, nil
	} else if w == 0 {
		w = int(float32(h) * sr)
	} else if h == 0 {
		h = (int)(float32(w) / sr)
	}

	x := 0
	y := 0
	nw := sw
	nh := sh

	ratio := float32(sw) / float32(sh)
	outputRatio := float32(w) / float32(h)
	if math.Abs(float64(ratio-outputRatio)) > 0.1 {
		if ratio < outputRatio {
			nh = int(float32(nw) / outputRatio)
			y = (sh - nh) / 2.0
		} else {
			nw = int(float32(nh) * outputRatio)
			x = (sw - nw) / 2.0
		}

		rect := image.Rect(x, y, x+nw, y+nh)
		src = SubImage(src, rect)
		log.Info(src.Bounds(), ratio, outputRatio)
	}

	dst := imaging.Resize(src, w, h, imaging.Lanczos)
	return dst, nil
}
Exemplo n.º 26
0
func (i *Image) Draw() image.Image {
	if i.canvas != nil && i.upToDate {
		return i.canvas
	}

	m, err := imaging.Open(i.href)
	if err != nil {
		return image.Transparent
	}

	if i.width|i.height != 0 {
		m = imaging.Resize(m, i.width, i.height, i.filter)
	}
	size := m.Bounds().Size()
	i.setDimensions(size.X, size.Y)

	return m
}
Exemplo n.º 27
0
//Resize with mode fit. Does the acutal resizing and returns the image
//errors only if dstWidth or dstHeight is invalid
func (f FitResizer) Resize(input image.Image, dstWidth, dstHeight int) (image.Image, error) {
	if dstWidth < 0 || dstHeight < 0 {
		return nil, fmt.Errorf("Please specify both width and height for your target image")
	}

	originalBounds := input.Bounds()
	originalRatio := float64(originalBounds.Dx()) / float64(originalBounds.Dy())

	targetRatio := float64(dstWidth) / float64(dstHeight)

	if targetRatio < originalRatio {
		dstHeight = int(float64(dstWidth) / originalRatio)
	} else {
		dstWidth = int(float64(dstHeight) * originalRatio)
	}

	return imaging.Resize(input, int(dstWidth), int(dstHeight), imaging.Lanczos), nil
}
Exemplo n.º 28
0
func (f *File) GenerateImage(width int, height int, crop bool) error {
	fpath := filepath.Join(f.TagDir, f.Filename)

	s, err := imaging.Open(fpath)
	if err != nil {
		return err
	}

	if crop {
		im := imaging.Fill(s, width, height, imaging.Center,
			imaging.Lanczos)
		err = imaging.Save(im, f.ImagePath(width, height))
	} else {
		im := imaging.Resize(s, width, height, imaging.Lanczos)
		err = imaging.Save(im, f.ImagePath(width, height))
	}
	return err
}
Exemplo n.º 29
0
func MakeFromReader(reader io.Reader, t string, w, h int) (image *image.NRGBA, err error) {
	srcImage, err := Open(reader)
	if err != nil {
		return nil, err
	}

	switch t {
	case "thumbnail":
		image = imaging.Thumbnail(srcImage, w, h, imaging.Lanczos)
	case "resize":
		image = imaging.Resize(srcImage, w, h, imaging.Lanczos)
	case "fit":
		image = imaging.Fit(srcImage, w, h, imaging.Lanczos)
	default:
		image = imaging.Thumbnail(srcImage, w, h, imaging.Lanczos)
	}

	return
}
Exemplo n.º 30
0
func mergeTextures(normalTexture, litTexture *image.NRGBA) {
	normSize := normalTexture.Bounds().Size()
	litSize := litTexture.Bounds().Size()
	if normSize.X != litSize.X || normSize.Y != litSize.Y {
		//Größen sind unterschiedlich --> normale Textur auf Größe der Nachttextur skalieren
		normalTexture = imaging.Resize(normalTexture, litSize.X, litSize.Y, imaging.Linear)
	}
	for x := 0; x < litSize.X; x++ {
		for y := 0; y < litSize.Y; y++ {
			i := y*normalTexture.Stride + x*4
			j := y*litTexture.Stride + x*4

			litTexture.Pix[j+0] = mergePixel(normalTexture.Pix[i+0], litTexture.Pix[j+0], 1.0)
			litTexture.Pix[j+1] = mergePixel(normalTexture.Pix[i+1], litTexture.Pix[j+1], 1.0)
			litTexture.Pix[j+2] = mergePixel(normalTexture.Pix[i+2], litTexture.Pix[j+2], 0.7)
			litTexture.Pix[j+3] = normalTexture.Pix[i+3]
		}
	}
}