Example #1
0
func main() {
	const zoom = 1.0
	const x, y = 0.0, 0.0

	img := fractal(size, size, x, y, zoom, maxIterations)
	imaging.Save(img, fmt.Sprintf("%.3f_%.3f_%.3f.png", x, y, zoom))

	if !animate {
		return
	}
	var wg sync.WaitGroup
	is := make(chan int)
	for procs := 0; procs < 4; procs++ {
		wg.Add(1)
		go func(is chan int) {
			defer wg.Done()
			for i := range is {
				frame := fractal(size, size, x-0.03*float64(i), y-0.006*float64(i), zoom+0.12*float64(i), maxIterations)
				imaging.Save(frame, fmt.Sprintf("frames/frame_%04d.png", i))
				println(i)
			}
		}(is)
	}
	for i := 0; i < 1500; i++ {
		is <- i
	}
	close(is)
	wg.Wait()
}
Example #2
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
}
Example #3
0
func (p *program) editImage(rot Rot, folder string, list []string) error {
	for _, item := range list {
		filename := filepath.Join(config.FileRoot, folder, item)
		fi, err := os.Stat(filename)
		if err != nil {
			return err
		}
		fullImage, err := imaging.Open(filename)
		if err != nil {
			return err
		}

		switch rot {
		case RotLeft:
			fullImage = imaging.Rotate90(fullImage)
		case RotRight:
			fullImage = imaging.Rotate270(fullImage)
		case RotFlip:
			fullImage = imaging.Rotate180(fullImage)
		default:
			return fmt.Errorf("Unknown rot value: %d", rot)
		}
		err = imaging.Save(fullImage, filename)
		if err != nil {
			return err
		}
		tm := fi.ModTime()
		err = os.Chtimes(filename, tm, tm)
		if err != nil {
			return err
		}
	}
	return p.refreshCache(folder, list)
}
Example #4
0
// 生成并保存缩略图
func MakeAndSaveThumbnailFromReader(reader io.Reader, toFile string, w, h int) error {
	tnImage, err := MakeThumbnailFromReader(reader, w, h)
	if err != nil {
		return err
	}
	return imaging.Save(tnImage, toFile)
}
Example #5
0
func (m *Manikyr) createThumb(root, parentFile string) {
	img, err := openImageWhenReady(parentFile)
	if err != nil {
		m.EmitEvent(root, Error, parentFile, err)
		return
	}

	localThumbs := m.ThumbDirGetter(parentFile)
	_, err = os.Stat(localThumbs)
	// If thumbDir does not exist...
	if os.IsNotExist(err) {
		// ..create it
		err := os.Mkdir(localThumbs, m.thumbDirPerms)
		if err != nil {
			m.EmitEvent(root, Error, localThumbs, err)
			return
		}
	} else if err != nil {
		m.EmitEvent(root, Error, localThumbs, err)
		return
	}

	// Save the thumbnail
	thumb := imaging.Thumbnail(img, m.thumbWidth, m.thumbHeight, m.thumbAlgo)
	thumbPath := path.Join(localThumbs, m.ThumbNameGetter(parentFile))
	if err = imaging.Save(thumb, thumbPath); err != nil {
		m.EmitEvent(root, Error, thumbPath, err)
		return
	}

	m.EmitEvent(root, ThumbCreate, thumbPath, nil)
}
Example #6
0
func thumbFile(filePath string) {
	src, _ := imaging.Open(filePath)
	var dst *image.NRGBA

	dst = imaging.Thumbnail(src, 48, 48, imaging.CatmullRom)
	imaging.Save(dst, filePath)
}
Example #7
0
func ProcessPhoto(photo *Photo) error {
	origImg, err := imaging.Open(GetPhotoPath(photo, "o"))
	if err != nil {
		return err
	}

	src := imaging.Clone(origImg)

	for _, sz := range PhotoSizes {
		var dst image.Image

		switch sz.Type {
		case "thumbnail":
			dst = imaging.Thumbnail(src, sz.Width, sz.Height, imaging.Lanczos)
		case "fit":
			dst = imaging.Fit(src, sz.Width, sz.Height, imaging.Lanczos)
		}

		err := imaging.Save(dst, GetPhotoPath(photo, sz.Suffix))
		if err != nil {
			return err
		}
	}

	return nil
}
Example #8
0
func ProcessAvatar(user *User) error {
	origImg, err := imaging.Open(GetAvatarPath(user, "o"))
	if err != nil {
		return err
	}

	src := imaging.Clone(origImg)

	for _, sz := range AvatarSizes {
		var dst image.Image

		switch sz.Type {
		case "thumbnail":
			dst = imaging.Thumbnail(src, sz.Width, sz.Height, imaging.Lanczos)
		case "fit":
			dst = imaging.Fit(src, sz.Width, sz.Height, imaging.Lanczos)
		}

		err := imaging.Save(dst, GetAvatarPath(user, sz.Suffix))
		if err != nil {
			return err
		}
	}

	return nil
}
Example #9
0
// 生成并保存缩略图
func MakeAndSaveThumbnail(fromFile string, toFile string, w, h int) error {
	tnImage, err := MakeThumbnail(fromFile, w, h)
	if err != nil {
		return err
	}
	return imaging.Save(tnImage, toFile)
}
Example #10
0
func MakeAndSaveFromReaderMaxWithMode(reader io.Reader, t string, toFile string, w, h int) error {
	tnImage, err := MakeFromReaderMaxWithMode(reader, t, w, h)
	if err != nil {
		return err
	}
	return imaging.Save(tnImage, toFile)
}
Example #11
0
func main() {
	fmt.Println("ImgNet loading...")
	netSize := []int{3, 3}
	net := NewImgNet(netSize[0], netSize[1])

	imgOrig, err := imaging.Open("lena-colour.png")
	if err != nil {
		panic(err)
	}

	imgFiltered, err := imaging.Open("lena-colourdiff.png")
	if err != nil {
		panic(err)
	}

	targetImg, err := imaging.Open("lena-colour.png")
	if err != nil {
		panic(err)
	}

	fmt.Println("Teaching network.")
	for randcount := 0; randcount < 1000000; randcount++ {
		x := rand.Intn(imgOrig.Bounds().Dx()-netSize[0]) - netSize[0]/2
		y := rand.Intn(imgOrig.Bounds().Dy()-netSize[1]) - netSize[1]/2
		net.FF(image.Pt(x, y), &imgOrig)
		net.BP(image.Pt(x, y), &imgFiltered)
	}

	fmt.Println("Filtering image.")
	result := net.Filter(targetImg)
	imaging.Save(result, "output.png")

}
Example #12
0
func main() {

	// input files
	files := []string{"01.png", "02.png", "03.png"}

	// load images and make 100x100 thumbnails of them
	var images []image.Image
	for _, file := range files {
		img, err := imaging.Open(file)
		if err != nil {
			panic(err)
		}
		images = append(images, img)
	}

	n := neuro.NewNetwork([]int{3, 3, 3})

	for y := 0; y < images[0].Bounds().Dy(); y++ {
		for x := 0; x < images[0].Bounds().Dx(); x++ {
			imgR, imgG, imgB, _ := images[0].At(x, y).RGBA()
			r := float64(imgR) / 65535
			g := float64(imgG) / 65535
			b := float64(imgB) / 65535
			n.FeedForward([]float64{r, g, b})

			imgR2, imgG2, imgB2, _ := images[1].At(x, y).RGBA()
			r2 := float64(imgR2) / 65535
			g2 := float64(imgG2) / 65535
			b2 := float64(imgB2) / 65535
			n.BackPropagation([]float64{r2, g2, b2})
		}
	}

	m := image.NewRGBA(image.Rect(0, 0, 128, 128))
	for y := 0; y < images[2].Bounds().Dy(); y++ {
		for x := 0; x < images[2].Bounds().Dx(); x++ {
			imgR, imgG, imgB, _ := images[2].At(x, y).RGBA()
			r := float64(imgR) / 65535
			g := float64(imgG) / 65535
			b := float64(imgB) / 65535
			n.FeedForward([]float64{r, g, b})
			results := n.Results()
			c := color.RGBA{uint8(results[0] * 255), uint8(results[1] * 255), uint8(results[2] * 255), 255}
			m.Set(x, y, c)
		}
	}

	dst := imaging.New(256, 256, color.NRGBA{0, 0, 0, 0})
	dst = imaging.Paste(dst, images[0], image.Pt(0, 0))
	dst = imaging.Paste(dst, images[1], image.Pt(128, 0))
	dst = imaging.Paste(dst, images[2], image.Pt(0, 128))
	dst = imaging.Paste(dst, m, image.Pt(128, 128))

	// save the combined image to file
	err := imaging.Save(dst, "dst.jpg")
	if err != nil {
		panic(err)
	}
}
Example #13
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
}
Example #14
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)
}
Example #15
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
}
Example #16
0
func (f *File) GenerateThumbnail() error {
	fpath := filepath.Join(f.TagDir, f.Filename)

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

	thumb := imaging.Fill(s, 75, 75, imaging.Center, imaging.NearestNeighbor)
	err = imaging.Save(thumb, f.ThumbnailPath())
	return err
}
Example #17
0
func main() {
	flag.Parse()

	if len(*destination) > 0 {
		err := os.MkdirAll(*destination, os.ModePerm)
		if err != nil {
			fmt.Printf("Unable to create destination: %s\n", err)
			os.Exit(1)
		}
	}

	extMatch := regexp.MustCompile(`\.[a-zA-Z0-9]+$`)

	filelist := flag.Args()
	// if len(filelist) == 0 {
	// 	filelist = []string{"./*.*"}
	// }

	for _, srcArg := range filelist {
		srcFilenames, err := filepath.Glob(srcArg)
		if err != nil {
			log.Printf("Glob error: %s\n", err)
			continue
		}
		for _, srcFilename := range srcFilenames {
			fmt.Printf("Processing [%s]... ", srcFilename)
			src, err := imaging.Open(srcFilename)
			if err != nil {
				log.Printf("error: %s\n", err)
				continue
			}
			dest := imaging.Grayscale(src)
			extension := *output
			if extension == "" {
				extension = strings.TrimLeft(filepath.Ext(srcFilename), ".")
			}
			destFilename := extMatch.ReplaceAllString(srcFilename, "") + fmt.Sprintf("-grayscale.%s", extension)
			if len(*destination) > 0 {
				_, file := filepath.Split(destFilename)
				destFilename = filepath.Join(*destination, file)
			}
			err = imaging.Save(dest, destFilename)
			if err != nil {
				log.Printf("error: %s\n", err)
				continue
			}
			fmt.Printf("OK; written to %s\n", destFilename)
		}
	}
}
Example #18
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)
			}
		}
	}
}
Example #19
0
// Rewrite Image to disk
func rewriteImage(dst *image.NRGBA, filename string) (int, error) {
	if r, _ := Exists(filename); r {
		os.Remove(filename)
	}

	// save the image to file
	if err := imaging.Save(dst, filename); err != nil {
		return 0, err
	}

	f, err := os.Stat(filename)
	if err != nil {
		return 0, err
	}

	return int(f.Size()), err
}
Example #20
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)
}
Example #21
0
func Resize(c *middleware.Context) {
	w := c.QueryInt("width")
	p := c.Req.URL.Path
	color.Green("[path] %s", p)
	target := strings.TrimPrefix(p, "/resize")
	if strings.HasPrefix(target, "/cat/screen/") {
		var id int64
		fmt.Sscanf(target, "/cat/screen/%d?width=", &id)
		name, e := screen(id)
		if e != nil {
			color.Red("%s", e)
			return
		}
		target = name
	}
	savePath := "data/public/resize/" + com.ToStr(w) + "/" + target + ".jpg"
	if com.IsFile(savePath) {
		f, e := os.Open(savePath)
		if e != nil {
			color.Red("%s", e)
		}
		c.Resp.Header().Set("Content-Type", "image/jpeg")
		io.Copy(c.Resp, f)
		return
	}

	img, e := imaging.Open(filepath.Join("data/uploads", target))
	if e != nil {
		color.Red("%s", e)
		return
	}
	i := resize.Resize(uint(w), uint(w/2), img, resize.Bilinear)
	dir := filepath.Dir(target)
	os.MkdirAll(filepath.Join("data/public/resize/"+com.ToStr(w)+"/", dir), 0777)
	e = imaging.Save(i, savePath)
	if e != nil {
		color.Red("%s", e)
	}
	c.Resp.Header().Set("Content-Type", "image/jpeg")
	e = jpeg.Encode(c.Resp, i, nil)
	if e != nil {
		color.Red("%s", e)
	}
	//c.Redirect("/public/resize/" + com.ToStr(w) + "/" + target + ".jpg")
}
Example #22
0
func main() {
	optarg.Header("General options")
	optarg.Add("h", "height", "image height", 100)
	optarg.Add("w", "width", "image width", 0)
	optarg.Add("i", "input", "input filename", "")
	optarg.Add("o", "output", "output filename", "")

	var (
		height  int
		width   int
		inName  string
		outName string
	)

	for opt := range optarg.Parse() {
		switch opt.ShortName {
		case "h":
			height = opt.Int()
		case "w":
			width = opt.Int()
		case "i":
			inName = opt.String()
		case "o":
			outName = opt.String()
		}
	}

	if inName == "" || outName == "" {
		optarg.Usage()
		log.Fatal()
	}

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

	dstImg := resize(orgImg, width, height)

	err = imaging.Save(dstImg, outName)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Resize to", outName)
}
Example #23
0
func main() {
	// use all CPU cores for maximum performance
	runtime.GOMAXPROCS(runtime.NumCPU())

	// input files
	files := []string{"1.jpg", "2.jpg", "3.jpg", "4.jpg"}

	// load images and make 100x100 thumbnails of them
	var thumbnails []image.Image
	for _, file := range files {
		img, err := imaging.Open(file)
		if err != nil {
			panic(err)
		}
		thumb := imaging.Thumbnail(img, 100, 100, imaging.CatmullRom)
		thumbnails = append(thumbnails, thumb)
	}

	// create a new blank image
	dst := imaging.New(100*len(thumbnails), 100, color.NRGBA{0, 0, 0, 0})

	f, err := os.OpenFile("db", os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	// paste thumbnails into the new image side by side
	for i, thumb := range thumbnails {
		if _, err = f.Write([]byte(thumb)); err != nil {
			panic(err)
		}
		dst = imaging.Paste(dst, thumb, image.Pt(i*100, 0))
	}

	// save the combined image to file
	err = imaging.Save(dst, "dst.jpg")
	if err != nil {
		panic(err)
	}
}
Example #24
0
func create_thumbnail(file string, thumbnail_name string) {
	img, err := imaging.Open(file)
	if err != nil {
		return
	}
	thumb := imaging.Thumbnail(img, 50, 50, imaging.CatmullRom)
	// thumbnails = append(thumbnails, thumb)

	// create a new blank image
	dst := imaging.New(50, 50, color.NRGBA{0, 0, 0, 0})

	// paste thumbnails into the new image side by side
	// for i, thumb := range thumbnails {
	dst = imaging.Paste(dst, thumb, image.Pt(0, 0))
	// }
	// save the combined image to file
	err = imaging.Save(dst, thumbnail_name)
	if err != nil {
		log.Println(err)
	}
}
Example #25
0
File: user.go Project: jsli/gorevel
func (c *User) EditPost(avatar string) revel.Result {
	id := c.RenderArgs["user"].(*models.User).Id
	checkFileExt(c.Controller, imageExts, "picture", "Only image")
	user := models.FindUserById(id)
	if user.Id == 0 {
		return c.NotFound("用户不存在")
	}

	if c.Validation.HasErrors() {
		c.Validation.Keep()
		c.FlashParams()
		return c.Redirect(routes.User.Edit())
	}

	if ok, _ := getFileExt(c.Request, "picture"); ok {
		picture := saveFile(c.Request, "picture")
		src, _ := imaging.Open(uploadPath + picture)
		var dst *image.NRGBA

		dst = imaging.Thumbnail(src, 48, 48, imaging.CatmullRom)
		avatar = "thumb" + picture
		imaging.Save(dst, uploadPath+avatar)
		deleteFile(picture)
	}

	if avatar != "" {
		if strings.HasPrefix(user.Avatar, "thumb") {
			deleteFile(user.Avatar)
		}
		user.Avatar = avatar
	}

	if user.Save() {
		c.Flash.Success("保存成功")
	} else {
		c.Flash.Error("保存信息失败")
	}

	return c.Redirect(routes.User.Edit())
}
Example #26
0
func do_params(ctx *context, ctrl *ext.Controller) bool {
	qr := ctrl.Request.Param("qrcode")
	if qr != "" {
		if size, err := strconv.ParseInt(qr, 10, 64); err == nil {
			return do_qrcode(ctx, ctrl, int(size))
		}
	}

	resize := ctrl.Request.Param("resize")
	if resize != "" {
		fn := path.Join(ctx.app.Options.StaticRoot, "resize", util.ResizeKey(ctrl.Request.URI(), resize))
		if util.Exist(fn) {
			ctrl.File(fn)
			return true
		}
		if rect, err := util.ParseRect(resize, "x"); err == nil {
			f1 := path.Join(ctx.app.Options.StaticRoot, ctrl.Request.URI())
			ctx.Info("f1 :%s", f1)
			if src, err := imaging.Open(f1); err == nil {
				dst := imaging.Resize(src, rect.Width, rect.Height, imaging.Lanczos)
				if err := imaging.Save(dst, fn); err == nil {
					ctrl.File(fn)
					return true
				}
			}
		}
	}

	fit := ctrl.Request.Param("fit")
	if fit != "" {
		fn := path.Join(ctx.app.Options.StaticRoot, "fit", util.ResizeKey(ctrl.Request.URI(), resize))
		if util.Exist(fn) {
			ctrl.File(fn)
			return true
		}
		if rect, err := util.ParseRect(resize, "x"); err == nil {
			f1 := path.Join(ctx.app.Options.StaticRoot, ctrl.Request.URI())
			if src, err := imaging.Open(f1); err == nil {
				dst := imaging.Fit(src, rect.Width, rect.Height, imaging.Lanczos)
				if err := imaging.Save(dst, fn); err == nil {
					ctrl.File(fn)
					return true
				}
			}
		}
	}

	thumbnail := ctrl.Request.Param("thumbnail")
	if thumbnail != "" {
		fn := path.Join(ctx.app.Options.StaticRoot, "thumbnail", util.ResizeKey(ctrl.Request.URI(), resize))
		if util.Exist(fn) {
			ctrl.File(fn)
			return true
		}
		if rect, err := util.ParseRect(thumbnail, "x"); err == nil {
			f1 := path.Join(ctx.app.Options.StaticRoot, ctrl.Request.URI())
			if src, err := imaging.Open(f1); err == nil {
				dst := imaging.Thumbnail(src, rect.Width, rect.Height, imaging.Lanczos)
				if err := imaging.Save(dst, fn); err == nil {
					ctrl.File(fn)
					return true
				}
			}
		}
	}

	return false
}
Example #27
0
func (image *Image) resizeThumbnail(errorChan chan error, srcImage image.Image) {
	dstImage := imaging.Thumbnail(srcImage, widthThumbnail, widthThumbnail, imaging.Lanczos)

	destination := "./data/images/thumbnail/" + image.Location
	errorChan <- imaging.Save(dstImage, destination)
}
Example #28
0
func main() {
	fmt.Println("Hello, world")
	fname := "P1070332.JPG"
	rname := "P1070332_rotate.JPG"
	sname := "P1070332_small.JPG"

	f, err := os.Open(fname)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	// Optionally register camera makenote data parsing - currently Nikon and
	// Canon are supported.
	exif.RegisterParsers(mknote.All...)

	x, err := exif.Decode(f)
	if err != nil {
		log.Fatal(err)
	}

	// Get Orientation
	orientation, err := x.Get(exif.Orientation)
	if err != nil {
		fmt.Println(exif.Model, " not fround")
		return
	}
	fmt.Println("Orientation", orientation.String())

	// Rotate
	var rotateImage *image.NRGBA
	openImage, err := imaging.Open(fname)
	if err != nil {
		fmt.Println(err)
		return
	}
	switch orientation.String() {
	case "1":
	// Do nothing
	case "2":
		rotateImage = imaging.FlipH(openImage)
	case "3":
		rotateImage = imaging.Rotate180(openImage)
	case "4":
		rotateImage = imaging.FlipV(openImage)
	case "5":
		rotateImage = imaging.Transverse(openImage)
	case "6":
		rotateImage = imaging.Rotate270(openImage)
	case "7":
		rotateImage = imaging.Transpose(openImage)
	case "8":
		rotateImage = imaging.Rotate90(openImage)
	}
	err = imaging.Save(rotateImage, rname)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(rname, " saved")

	// Small
	var smallImage *image.NRGBA
	if rotateImage.Rect.Dx() > rotateImage.Rect.Dy() {
		smallImage = imaging.Resize(rotateImage, 1920, 0, imaging.Lanczos)
	} else {
		smallImage = imaging.Resize(rotateImage, 0, 1920, imaging.Lanczos)
	}
	err = imaging.Save(smallImage, sname)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(sname, " saved")

	// Use jpeg.Encode() to write to a file
	// https://github.com/disintegration/imaging/blob/master/helpers.go#L79
	// func Encode(w io.Writer, m image.Image, o *Options) error
	// https://golang.org/pkg/image/jpeg/
}
Example #29
0
func (a *Api) Create(data []byte, name string, descr string) (Img, error) {
	named := true
	bts := bytes.NewReader(data)
	img, _, err := image.Decode(bts)
	if err != nil {
		return Img{}, err
	}

	tm := time.Now()

	if name == "" || len(name) <= int(a.nesting) {
		name = randName()
		named = false
	}

	for {
		found, err := a.ExistName(name)
		if err != nil {
			return Img{}, err
		}
		if found {
			name = randName()
		}
		if !found {
			break
		}
	}

	path := a.path

	for i := uint8(0); i < a.nesting; i++ {
		path += "/" + name[i:i+1]
	}

	os.MkdirAll(path, 0777)
	for _, v := range a.sizes {
		save_path := path + "/" + name + "_" + strconv.Itoa(v.Width) + "x" +
			strconv.Itoa(v.Height)
		save_path_with_ex := save_path + ".jpg"
		if v.Crop == "thumb" {
			c := imaging.Thumbnail(img, v.Width, v.Height, imaging.Lanczos)
			imaging.Save(c, save_path_with_ex)
		} else if v.Crop == "fit" {
			c := imaging.Fit(img, v.Width, v.Height, imaging.Lanczos)
			imaging.Save(c, save_path_with_ex)
		}
		if a.WebpAddr != "" {
			cmd := exec.Command(a.WebpAddr, save_path_with_ex, "-o",
				save_path+".webp")
			err := cmd.Run()
			if err != nil {
				fmt.Println(err)
				return Img{}, errors.New("Webp Not Working")
			}
		}

	}
	out, err := os.Create(path + "/" + name + ".jpg")
	if err != nil {
		return Img{}, err
	}
	defer out.Close()
	jpeg.Encode(out, img, nil)

	if a.WebpAddr != "" {
		cmd := exec.Command(a.WebpAddr, path+"/"+name+".jpg", "-o",
			path+"/"+name+".webp")
		err := cmd.Run()
		if err != nil {
			fmt.Println(err)
			return Img{}, errors.New("Webp Not Working")
		}
	}

	im := Img{
		Name:        name,
		Description: descr,
		Named:       named,
		Created:     tm.UnixNano(),
		Updated:     tm.UnixNano(),
	}

	err = a.Db.Insert(&im)
	if err != nil {
		return Img{}, err
	}
	return im, nil
}
Example #30
0
func handleStuff() {
	conn := Redis.Get()

	defer func() {
		if r := recover(); r != nil {
			handleStuff()
		}
	}()

	for {
		log.Println("Waiting on new image...")

		ids, err := redis.Strings(conn.Do("BLPOP", "uploads", 0))
		if err != nil {
			doError(err)
			continue
		}

		id := ids[1]

		log.Printf("Found ID %v", ids)
		time.Sleep(2 * time.Second)

		if id == "" {
			log.Println("No new uploads found")
			time.Sleep(5 * time.Second)
		}

		img := &models.Image{}
		query := Db.Where("uuid = ?", id).First(img)
		if query.Error != nil {
			defer conn.Do("RPUSH", "uploads", id)
			doError(query.Error)
			continue
		}

		log.Printf("Starting to process image %d:%s", img.ID, img.UUID)

		image, err := imaging.Open(Config.Storage.Path + "/" + img.UUID + "/" + img.Filename)
		if err != nil {
			defer conn.Do("RPUSH", "uploads", id)
			doError(err)
			continue
		}

		croppedImage := imaging.Thumbnail(image, 256, 256, imaging.Lanczos)
		if err != nil {
			defer conn.Do("RPUSH", "uploads", id)
			doError(err)
			continue
		}

		err = imaging.Save(croppedImage, Config.Storage.Path+"/"+img.UUID+"/thumbnail.png")
		if err != nil {
			defer conn.Do("RPUSH", "uploads", id)
			doError(err)
			continue
		}

		log.Printf(
			"Wrote thumbnail for image %d:%s",
			img.ID,
			img.UUID,
		)
	}

	conn.Close()
}