Пример #1
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")

}
Пример #2
0
func openImageWhenReady(file string) (image.Image, error) {
	// Retry opening the image until err != image.ErrFormat
	// or the next retry would take over a minute.
	// FIXME

	var img image.Image
	var err error
	var retry int
	var t time.Duration

	for {
		t = time.Duration(1000 * (retry * 2))
		time.Sleep(time.Millisecond * t)

		img, err = imaging.Open(file)
		if err == image.ErrFormat {
			retry = retry + 1
			if retry*2 > 60 {
				break
			}
			continue
		}
		break
	}
	return img, err
}
Пример #3
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
}
Пример #4
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)
}
Пример #5
0
func openImage(fileName string) image.Image {
	img, err := imaging.Open(testDir + fileName)
	if err != nil {
		log.Fatalln(err)
	}
	return img
}
Пример #6
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)
}
Пример #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
}
Пример #8
0
func (ths *ImageTagServer) go_get_image(w http.ResponseWriter, r *http.Request) {
	path := r.URL.Query().Get("path")
	path = ths.imgRoot + path
	path = strings.Replace(path, "..", "", -1)

	info, infoErr := os.Stat(path)
	if infoErr != nil {
		http.Error(w, infoErr.Error(), http.StatusInternalServerError)
		return
	}

	if info.IsDir() == true {
		http.Error(w, "No an image", http.StatusBadRequest)
		return
	}

	img, err := imaging.Open(path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Add("Content-Type", "image/jpeg")
	err = imaging.Encode(w, img, imaging.JPEG)
	if err != nil {
		http.Error(w, "Failed to thumbNail image", http.StatusInternalServerError)
		return
	}

}
Пример #9
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)
	}
}
Пример #10
0
// 生成缩略图
func MakeThumbnail(fromFile string, w, h int) (image *image.NRGBA, err error) {
	srcImage, err := imaging.Open(fromFile)
	if err != nil {
		return nil, err
	}

	image = imaging.Thumbnail(srcImage, w, h, imaging.Lanczos)
	return
}
Пример #11
0
//打开图片文件
func (this *Image) open(filename string) error {

	src, err := imaging.Open(filename)
	if err != nil {
		return err
	}
	this.filename = filepath.Base(filename)
	this.source = src
	return nil
}
Пример #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
}
Пример #13
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
}
Пример #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
}
Пример #15
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)
		}
	}
}
Пример #16
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)
			}
		}
	}
}
Пример #17
0
func getImage(filename string, small bool) (io.ReadCloser, error) {
	if !small {
		return os.Open(filename)
	}

	fullImage, err := imaging.Open(filename)
	if err != nil {
		return nil, err
	}
	resized := imaging.Fit(fullImage, config.SmallRes, config.SmallRes, imaging.Linear)

	r, w := io.Pipe()
	go imaging.Encode(w, resized, imaging.JPEG)
	return r, nil
}
Пример #18
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)
}
Пример #19
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")
}
Пример #20
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
}
Пример #21
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
}
Пример #22
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)
	}
}
Пример #23
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)
	}
}
Пример #24
0
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())
}
Пример #25
0
func (image *Image) CreateResizedImages() error {
	//generate an image from file
	srcImage, err := imaging.Open("./data/images/" + image.Location)
	if err != nil {
		return err
	}

	//create a channel to receive errors on
	errorChan := make(chan error)

	//process each resize
	go image.resizePreview(errorChan, srcImage)
	go image.resizeThumbnail(errorChan, srcImage)

	//wait for images to finish resizing
	for i := 0; i < 2; i++ {
		err = <-errorChan
		if err != nil {
			return err
		}
	}
	return nil
}
Пример #26
0
func thumbnailHandler(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
	height, err := strconv.Atoi(query.Get("height"))
	if err != nil {
		height = 50
	}
	path := filepath.Join(storage, r.URL.Path)
	photo, err := imaging.Open(path)
	if err != nil {
		fmt.Fprint(w, err)
		return
	}
	switch readRotation(path) {
	case 8:
		photo = imaging.Rotate90(photo)
	case 2:
		photo = imaging.Rotate180(photo)
	case 6:
		photo = imaging.Rotate270(photo)
	}
	thumb := imaging.Resize(photo, 0, height, imaging.Box)
	imaging.Encode(w, thumb, imaging.JPEG)
}
Пример #27
0
// Create HD and Thumbs Photos
func CreatePhotos(a *model.Album, p *model.Photo) (err error) {
	src, err := imaging.Open(a.PathSource() + p.OriginalName)
	if err != nil {
		return err
	}

	var dst *image.NRGBA
	filename := a.PathHD() + p.Filename
	log.Printf("Saving HD: %s\n", filename)
	dst = imaging.Fit(src, cfg.Image.MaxWidth, cfg.Image.MaxHeight, imaging.Lanczos)
	size, err := rewriteImage(dst, filename)
	if err != nil {
		return err
	}

	p.FileSizeHD = size
	filename = a.PathThumbs() + p.Filename
	log.Printf("Saving Thumb: %s\n", filename)
	dst = imaging.Thumbnail(dst, cfg.Image.ThumbWidth, cfg.Image.ThumbHeight, imaging.CatmullRom) // resize and crop the image to make a 200x200 thumbnail
	_, err = rewriteImage(dst, filename)

	return err
}
Пример #28
0
func (ths *ImageTagServer) go_thumb_image(w http.ResponseWriter, r *http.Request) {
	imgPath := r.URL.Query().Get("path")
	path := imgPath
	path = ths.imgRoot + path
	path = strings.Replace(path, "..", "", -1)

	info, infoErr := os.Stat(path)
	if infoErr != nil {
		http.Error(w, infoErr.Error(), http.StatusInternalServerError)
		return
	}

	db := ths.get_db()
	if db == nil {
		return
	}
	defer db.Close()

	row, rerr := db.Query("SELECT Thumb FROM Image WHERE Path LIKE '" + imgPath + "';")
	if rerr != nil {
		log.Println(rerr.Error())
		http.Error(w, rerr.Error(), http.StatusInternalServerError)
		return
	}

	if row.Next() {
		var result string
		e := row.Scan(&result)
		if e != nil {
			log.Println(e.Error())
			http.Error(w, e.Error(), http.StatusInternalServerError)
			return
		}
		b, _ := base64.StdEncoding.DecodeString(result)

		w.Header().Add("Content-Type", "image/jpeg")
		w.Write(b)
		return
	}

	if info.IsDir() == true {
		http.Error(w, "No an image", http.StatusBadRequest)
		return
	}

	img, err := imaging.Open(path)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	thumb := imaging.Thumbnail(img, 300, 300, imaging.CatmullRom)

	buffer := bytes.NewBuffer(nil)
	imaging.Encode(buffer, thumb, imaging.JPEG)
	b64 := base64.StdEncoding.EncodeToString(buffer.Bytes())

	insertRes, insertResErr := db.Exec("INSERT INTO Image(Path,Thumb) VALUES('" + imgPath + "','" + b64 + "');")
	if insertResErr != nil {
		log.Println(insertResErr.Error())
		http.Error(w, insertResErr.Error(), http.StatusInternalServerError)
		return
	}
	iid, _ := insertRes.LastInsertId()
	log.Println("Added image \"" + imgPath + "\" with id " + strconv.FormatInt(iid, 10))

	w.Header().Add("Content-Type", "image/jpeg")
	w.Write(buffer.Bytes())
	if err != nil {
		http.Error(w, "Failed to thumbNail image", http.StatusInternalServerError)
		return
	}

}
Пример #29
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
}
Пример #30
0
func (p *program) downloadWriteKey(key string, w http.ResponseWriter) error {
	bl, found := downloadMapper[key]
	if !found {
		http.Error(w, "Not found", 404)
		return nil
	}

	w.Header().Set("Content-Disposition", `attachment; filename="photos.tar"`)

	tw := tar.NewWriter(w)

	result := &bytes.Buffer{}

	for _, item := range bl.list {
		filename := filepath.Join(config.FileRoot, bl.folder, item)
		fi, err := os.Stat(filename)
		if err != nil {
			return err
		}
		if !bl.small {
			header, err := tar.FileInfoHeader(fi, "")
			if err != nil {
				return err
			}
			err = tw.WriteHeader(header)
			if err != nil {
				return err
			}
			f, err := os.Open(filename)
			if err != nil {
				return err
			}
			_, err = io.Copy(tw, f)
			f.Close()
			if err != nil {
				return err
			}
		} else {
			fullImage, err := imaging.Open(filename)
			if err != nil {
				return err
			}
			resized := imaging.Fit(fullImage, config.SmallRes, config.SmallRes, imaging.Linear)

			err = imaging.Encode(result, resized, imaging.JPEG)
			if err != nil {
				return err
			}

			header := &tar.Header{
				Name:    item,
				Size:    int64(result.Len()),
				Mode:    0666,
				ModTime: fi.ModTime(),
			}
			err = tw.WriteHeader(header)
			if err != nil {
				return err
			}
			_, err = io.Copy(tw, result)
			if err != nil {
				return err
			}
			result.Reset()
		}
	}

	return tw.Close()
}