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 }
// 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.Thumbnail(m, w, h, resampleFilter) } } } // 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 }
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 }
func thumbFile(filePath string) { src, _ := imaging.Open(filePath) var dst *image.NRGBA dst = imaging.Thumbnail(src, 48, 48, imaging.CatmullRom) imaging.Save(dst, filePath) }
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 }
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 }
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 }
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) }
func MakeThumbnailFromReader(reader io.Reader, w, h int) (image *image.NRGBA, err error) { srcImage, err := Open(reader) if err != nil { return nil, err } image = imaging.Thumbnail(srcImage, w, h, imaging.Lanczos) return }
// 生成缩略图 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 }
//Creating a thumbnail from a mp4 is complex so I cheat and use FFMPEG to create a JPEG... //JPEG is straightforwards // but ffmpeg probably can't make a thumbnail from a piped reader, so this only works if our //ReadSeeker is actually an *os.File func (m *Mp4Video) Thumbnail(in io.ReadSeeker, longSide int) (io.ReadSeeker, string, error) { var cmd *exec.Cmd if file, ok := in.(*os.File); ok { //this is the best way as ffmpeg can seek. cmd = exec.Command("ffmpeg", "-i", "/dev/fd/3", "-vframes", "1", "-f", "image2", "-") cmd.ExtraFiles = []*os.File{file} } else { log.Println("mp4thumb: using stdin (will probably fail...)") cmd = exec.Command("ffmpeg", "-i", "-", "-vframes", "1", "-f", "image2", "-") cmd.Stdin = in } stdout, err := cmd.StdoutPipe() //cmd.Stderr = os.Stderr if err != nil { return nil, "", err } if err := cmd.Start(); err != nil { return nil, "", err } img, err := jpeg.Decode(stdout) if err != nil { return nil, "", err } if err := cmd.Wait(); err != nil { return nil, "", err } //now we should have a jpeg to resize! var w, h int aspect := float64(m.Width) / float64(m.Height) if m.Width > m.Height { w, h = longSide, int(float64(longSide)/aspect) } else { w, h = int(float64(longSide)*aspect), longSide } switch m.Orientation { case photo.OrientedNormal90, photo.OrientedNormal270: //flip then rotate 270 w, h = h, w } //now create thumbnail. img = imaging.Thumbnail(img, w, h, imaging.Box) //rotate if needed. switch m.Orientation { case photo.OrientedNormal90: //rotate 90 (270 anticlockwise) img = imaging.Rotate270(img) case photo.OrientedNormal180: //rotate 180 img = imaging.Rotate180(img) case photo.OrientedNormal270: //rotate 270 (90 anti-clockwise) img = imaging.Rotate90(img) } var wr bytes.Buffer err = jpeg.Encode(&wr, img, nil) return bytes.NewReader(wr.Bytes()), "image/jpeg", err }
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 }
//Creating a thumbnail from a JPEG is straightforwards func (p *JpegPhoto) Thumbnail(in io.ReadSeeker, longSide int) (io.ReadSeeker, string, error) { //first we need to read the image. img, _, err := image.Decode(in) if err != nil { return nil, "", err } var w, h int aspect := float64(p.Width) / float64(p.Height) if p.Width > p.Height { w, h = longSide, int(float64(longSide)/aspect) } else { w, h = int(float64(longSide)*aspect), longSide } //we need to do this switch twice. first to check if we need to swap width/height //as we resize before rotation/flip //then after to do the resize/flip. switch p.Orientation { case OrientedNormal90, OrientedMirror90, OrientedNormal270, OrientedMirror270: //flip then rotate 270 w, h = h, w } //now create thumbnail. img = imaging.Thumbnail(img, w, h, imaging.Box) //now we need to rotate/flip it to match the ExifOrientation flag switch p.Orientation { case OrientedNormal: //nothing case OrientedMirror: //flip only img = imaging.FlipH(img) case OrientedNormal90: //rotate 90 img = imaging.Rotate90(img) case OrientedMirror90: //flip and rotate 90 img = imaging.FlipH(imaging.Rotate90(img)) case OrientedNormal180: //rotate 180 img = imaging.Rotate180(img) case OrientedMirror180: //flip then rotate 180 img = imaging.FlipH(imaging.Rotate180(img)) case OrientedNormal270: //rotate 270 (90 anti-clockwise) img = imaging.Rotate270(img) case OrientedMirror270: //flip then rotate 270 img = imaging.FlipH(imaging.Rotate270(img)) } //now re-encode var wr bytes.Buffer err = jpeg.Encode(&wr, img, nil) return bytes.NewReader(wr.Bytes()), "image/jpeg", err }
func maskImage(dst draw.Image, filename string) { infile, err := os.Open(filename) defer infile.Close() if err != nil { term.OutputError(fmt.Sprintf("Unable to open overlay image - %s", err.Error())) } else { overlay, _, err := image.Decode(infile) if err != nil { term.OutputError(fmt.Sprintf("Unable to decode image file - %s", err.Error())) } else { mask := image.NewUniform(color.Alpha{128}) draw.DrawMask(dst, dst.Bounds(), imaging.Thumbnail(overlay, 480, 480, imaging.CatmullRom), image.Pt(0, 0), mask, image.Pt(0, 0), draw.Over) } } }
//Resize with mode crop. Does the acutal resizing and returns the image //errors only if dstWidth or dstHeight is invalid func (c CropResizer) 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") } originalBounds := input.Bounds() originalRatio := float64(originalBounds.Dx()) / float64(originalBounds.Dy()) if dstWidth < 0 { dstWidth = int(float64(dstHeight) * originalRatio) } if dstHeight < 0 { dstHeight = int(float64(dstWidth) / originalRatio) } return imaging.Thumbnail(input, dstWidth, dstHeight, imaging.Lanczos), nil }
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) } }
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) } }
func MakeFromReaderMax(reader io.Reader, maxW, maxH int) (image *image.NRGBA, err error) { srcImage, err := Open(reader) if err != nil { return nil, err } srcBounds := srcImage.Bounds() w := srcBounds.Dx() h := srcBounds.Dy() if w > maxW { w = maxW } if h > maxH { h = maxH } image = imaging.Thumbnail(srcImage, w, h, imaging.Lanczos) return }
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()) }
func createImage(selection ArtistTrackList, output_filename string, overlay string) { if len(selection) != 9 { term.OutputError("Unable to find enough images to make cover") } else { term.OutputMessage(term.Yellow + "Generating image.." + term.Reset) xt := 3 yt := 3 width := xt * 160 height := yt * 160 dst := image.NewRGBA(image.Rect(0, 0, width, height)) count := 0 for y := 0; y < yt; y++ { for x := 0; x < xt; x++ { term.OutputMessage(term.Yellow + "." + term.Reset) src := selection[count].Tracks[0].CoverImage draw.Draw(dst, image.Rect(x*160, y*160, (x+1)*160, (y+1)*160), imaging.Thumbnail(src, 160, 160, imaging.CatmullRom), image.Pt(0, 0), draw.Src) count = count + 1 } } if overlay != "" { term.OutputMessage(term.Yellow + "." + term.Reset) maskImage(dst, overlay) term.OutputMessage(term.Yellow + "." + term.Reset) } f, err := os.Create(output_filename) if err != nil { term.OutputError("\ncant save picture: " + err.Error()) } defer f.Close() term.OutputMessage(term.Yellow + "." + term.Reset) jpeg.Encode(f, dst, nil) term.OutputMessage(term.Yellow + term.Bold + "DONE!\n" + term.Reset) } }
// 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 }
func (imageHandler) Handle(media MediaLibrary, file multipart.File, option *Option) error { if err := media.Store(media.URL("original"), option, file); err == nil { file.Seek(0, 0) if img, err := imaging.Decode(file); err == nil { if format, err := getImageFormat(media.URL()); err == nil { if cropOption := media.GetCropOption("original"); cropOption != nil { img = imaging.Crop(img, *cropOption) } // Save default image var buffer bytes.Buffer imaging.Encode(&buffer, img, *format) media.Store(media.URL(), option, &buffer) for key, size := range media.GetSizes() { newImage := img if cropOption := media.GetCropOption(key); cropOption != nil { newImage = imaging.Crop(newImage, *cropOption) } dst := imaging.Thumbnail(newImage, size.Width, size.Height, imaging.Lanczos) var buffer bytes.Buffer imaging.Encode(&buffer, dst, *format) media.Store(media.URL(key), option, &buffer) } return nil } else { return err } } else { return err } } else { return err } }
// transformImage modifies the image m based on the transformations specified // in opt. func transformImage(m image.Image, opt Options) image.Image { // convert percentage width and height values to absolute values imgW := m.Bounds().Max.X - m.Bounds().Min.X imgH := m.Bounds().Max.Y - m.Bounds().Min.Y var w, h int if 0 < opt.Width && opt.Width < 1 { w = int(float64(imgW) * opt.Width) } else if opt.Width < 0 { w = 0 } else { w = int(opt.Width) } if 0 < opt.Height && opt.Height < 1 { h = int(float64(imgH) * opt.Height) } else if opt.Height < 0 { h = 0 } else { h = int(opt.Height) } // never resize larger than the original image if !opt.ScaleUp { if w > imgW { w = imgW } if h > imgH { h = imgH } } // resize if w != 0 || h != 0 { 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.Thumbnail(m, w, h, resampleFilter) } } } // 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 }
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 }
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) }
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() }
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 }
func main() { app := cli.NewApp() app.Author = "zujko" app.Name = "img-go" app.Usage = "INSERT USAGE HERE" app.Commands = []cli.Command{ { Name: "resize", Aliases: []string{"r"}, Usage: "Resizes the image", Action: func(c *cli.Context) { if len(c.Args()) >= 2 { img, err := imaging.Open(c.Args()[0]) if err != nil { color.Red("Error opening image") } else { size := strings.Split(c.Args()[1], "x") width, we := strconv.Atoi(size[0]) height, he := strconv.Atoi(size[1]) if we != nil || he != nil { color.Red("Invalid dimension arguments") return } if width > 1000 || height > 1000 { color.Red("Dimensions are too large") return } resized := imaging.Thumbnail(img, width, height, imaging.CatmullRom) resizeName := "resized.jpg" if len(c.Args()) == 3 { resizeName = c.Args()[2] } err := imaging.Save(resized, resizeName) if err != nil { color.Red("Error saving image") } else { color.Green("Image resized") } } } else { fmt.Println("usage: image_name size [output_name]") } }, }, { Name: "blur", Aliases: []string{"bl"}, Usage: "Adds a blur to the image", Action: func(c *cli.Context) { if len(c.Args()) < 2 { fmt.Println("usage: image_name blur_amount [output_name]") } else { img, err := imaging.Open(c.Args()[0]) if err != nil { color.Red("Error opening Image") return } blurAmt, er := strconv.ParseFloat(c.Args()[1], 64) if er != nil { color.Red("Invalid arguments") return } dstImage := imaging.Blur(img, blurAmt) imgName := "blur.jpg" if len(c.Args()) == 3 { imgName = c.Args()[2] } saveErr := imaging.Save(dstImage, imgName) if saveErr != nil { color.Red("Error saving image") } else { color.Green("Image blurred") } } }, }, { Name: "brighten", Aliases: []string{"br"}, Usage: "Brighten or darken the image", Action: func(c *cli.Context) { //BRIGHTEN IMAGE }, }, } app.Run(os.Args) }
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 } }
func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request, isGetMethod bool) { n := new(storage.Needle) vid, fid, filename, ext, _ := parseURLPath(r.URL.Path) volumeId, err := storage.NewVolumeId(vid) if err != nil { glog.V(2).Infoln("parsing error:", err, r.URL.Path) w.WriteHeader(http.StatusBadRequest) return } err = n.ParsePath(fid) if err != nil { glog.V(2).Infoln("parsing fid error:", err, r.URL.Path) w.WriteHeader(http.StatusBadRequest) return } glog.V(4).Infoln("volume", volumeId, "reading", n) if !vs.store.HasVolume(volumeId) { lookupResult, err := operation.Lookup(vs.masterNode, volumeId.String()) glog.V(2).Infoln("volume", volumeId, "found on", lookupResult, "error", err) if err == nil && len(lookupResult.Locations) > 0 { http.Redirect(w, r, "http://"+lookupResult.Locations[0].PublicUrl+r.URL.Path, http.StatusMovedPermanently) } else { glog.V(2).Infoln("lookup error:", err, r.URL.Path) w.WriteHeader(http.StatusNotFound) } return } cookie := n.Cookie count, e := vs.store.Read(volumeId, n) glog.V(4).Infoln("read bytes", count, "error", e) if e != nil || count <= 0 { glog.V(0).Infoln("read error:", e, r.URL.Path) w.WriteHeader(http.StatusNotFound) return } if n.Cookie != cookie { glog.V(0).Infoln("request", r.URL.Path, "with unmaching cookie seen:", cookie, "expected:", n.Cookie, "from", r.RemoteAddr, "agent", r.UserAgent()) w.WriteHeader(http.StatusNotFound) return } if n.LastModified != 0 { w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat)) if r.Header.Get("If-Modified-Since") != "" { if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil { if t.Unix() >= int64(n.LastModified) { w.WriteHeader(http.StatusNotModified) return } } } } if n.NameSize > 0 && filename == "" { filename = string(n.Name) dotIndex := strings.LastIndex(filename, ".") if dotIndex > 0 { ext = filename[dotIndex:] } } mtype := "" if ext != "" { mtype = mime.TypeByExtension(ext) } if n.MimeSize > 0 { mtype = string(n.Mime) } if mtype != "" { w.Header().Set("Content-Type", mtype) } if filename != "" { w.Header().Set("Content-Disposition", "filename="+fileNameEscaper.Replace(filename)) } if ext != ".gz" { if n.IsGzipped() { if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { w.Header().Set("Content-Encoding", "gzip") } else { if n.Data, err = storage.UnGzipData(n.Data); err != nil { glog.V(0).Infoln("lookup error:", err, r.URL.Path) } } } } if ext == ".png" || ext == ".jpg" || ext == ".gif" { if srcImage, _, err := image.Decode(bytes.NewReader(n.Data)); err == nil { width, height := 0, 0 if r.FormValue("width") != "" { width, _ = strconv.Atoi(r.FormValue("width")) } if r.FormValue("height") != "" { height, _ = strconv.Atoi(r.FormValue("height")) } if width != 0 || height != 0 { bounds := srcImage.Bounds() var dstImage *image.NRGBA if width == height && bounds.Dx() != bounds.Dy() { dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos) } else { dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos) } var buf bytes.Buffer switch ext { case ".png": png.Encode(&buf, dstImage) case ".jpg": jpeg.Encode(&buf, dstImage, nil) case ".gif": gif.Encode(&buf, dstImage, nil) } n.Data = buf.Bytes() } } } w.Header().Set("Content-Length", strconv.Itoa(len(n.Data))) if isGetMethod { if _, e = w.Write(n.Data); e != nil { glog.V(0).Infoln("response write error:", e) } } }