//download image from town func (t *Townparser) downloadImage(url string, name string) error { defer func() { if err := recover(); err != nil { log.Info("%s recovered from panic", TAG) return } }() if url == "0" { return nil } exist, err := exists("templates/static/images/" + name + ".jpg") if err != nil { log.Error("%s %s", TAG, err.Error()) } if !exist { resp, err := t.Tc.Get(url) if err != nil { log.Error("%s image download failed, name: %v, url: %v", TAG, name, url) log.Error("%s %s", TAG, err.Error()) return err } defer resp.Body.Close() if strings.Contains(url, "jpg") || strings.Contains(url, "jpeg") { img, _ := jpeg.Decode(resp.Body) m := resize.Resize(300, 0, img, resize.Lanczos2Lut) out, err := os.Create("templates/static/images/" + name + ".jpg") if err != nil { log.Error("%s %s", TAG, err.Error()) return nil } // write new image to file jpeg.Encode(out, m, nil) out.Close() } else if strings.Contains(url, "png") { img, err := png.Decode(resp.Body) if err != nil { log.Error("%s %s", TAG, err.Error()) } m := resize.Resize(300, 0, img, resize.Lanczos2Lut) out, err := os.Create("templates/static/images/" + name + ".png") if err != nil { log.Error("%s %s", TAG, err.Error()) return nil } // write new image to file jpeg.Encode(out, m, nil) out.Close() } } time.Sleep(200 * time.Millisecond) return nil }
func thumbnailHandler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { filename, err := url.QueryUnescape(r.URL.String()) checkErr(err) fmt.Println("handling request for", filename) file, err := os.Open(filename) checkErr(err) defer file.Close() img, filetype, err := image.Decode(file) checkErr(err) var newImage image.Image if thumbnailSize < img.Bounds().Dx() || thumbnailSize < img.Bounds().Dy() { if img.Bounds().Dx() > img.Bounds().Dy() { newImage = resize.Resize(uint(thumbnailSize), 0, img, resize.Lanczos3) } else { newImage = resize.Resize(0, uint(thumbnailSize), img, resize.Lanczos3) } } else { newImage = img } switch filetype { case "png": err = png.Encode(w, newImage) case "gif": err = gif.Encode(w, newImage, nil) case "jpeg", "jpg": err = jpeg.Encode(w, newImage, nil) case "bmp": err = bmp.Encode(w, newImage) case "tiff": err = tiff.Encode(w, newImage, nil) default: // not sure how you got here but what are we going to do with you? fmt.Println("Unknown image type: ", filetype) io.Copy(w, file) } checkErr(err) fmt.Println("done handling request") }) }
func (p *photo) Transform(crop image.Rectangle, width, height uint, dontenlarge bool, format string, resample resize.InterpolationFunction) (Image, error) { img, err := p.Image() if err != nil { return nil, e.Forward(err) } imgResized := img if !(width == 0 && height == 0) { rect := img.Bounds() w := uint(rect.Max.X - rect.Min.X) h := uint(rect.Max.Y - rect.Min.Y) if (width >= w || height >= h) && !dontenlarge { imgResized = resize.Resize(width, height, img, resample) } else if width < w && height < h { imgResized = resize.Resize(width, height, img, resample) } } b := make([]byte, 0, 1024) buf := bytes.NewBuffer(b) err = jpeg.Encode(buf, imgResized, nil) if err != nil { return nil, e.Forward(err) } return &photo{Buf: buf.Bytes()}, nil }
func resizeImage(im image.Image, width int, height int) image.Image { if width > height { return resize.Resize(0, uint(height), im, resize.Lanczos3) } return resize.Resize(uint(width), 0, im, resize.Lanczos3) }
//funcion resize imagen func (u Util) ImgRZ(s string) { //cargamos archivo de imageb jpg file, err := os.Open("static/images/fotos_ori/" + s) if err != nil { log.Fatal("en este 1", err) } // decode jpeg image.Image img, err := jpeg.Decode(file) if err != nil { log.Fatal("en este 2", err) } file.Close() // resize to width 1000 using Lanczos resampling // and preserve aspect ratio m := resize.Resize(216, 162, img, resize.Lanczos3) out, err := os.Create("static/images/fotos_rz/" + s) if err != nil { log.Fatal(err) } defer out.Close() // write new image to file jpeg.Encode(out, m, nil) return }
// Make thumbnail for the selected file func MakeThumb(src string, dst_sane string, dst_thumb string) error { file, err := os.Open(src) defer file.Close() if err != nil { return err } img, err := jpeg.Decode(file) if err != nil { return err } sane := resize.Resize(1080, 0, img, resize.Bilinear) out_sane, err := os.Create(dst_sane) if err != nil { return err } defer out_sane.Close() jpeg.Encode(out_sane, sane, nil) thumb := resize.Thumbnail(200, 200, img, resize.Bilinear) out_thumb, err := os.Create(dst_thumb) if err != nil { return err } defer out_thumb.Close() jpeg.Encode(out_thumb, thumb, nil) return nil }
func createSmallPic(file io.Reader, fileSmall string, w, h int) error { // decode jpeg into image.Image img, err := jpeg.Decode(file) if err != nil { return err } b := img.Bounds() if w > b.Dx() { w = b.Dx() } if h > b.Dy() { h = b.Dy() } // resize to width 1000 using Lanczos resampling // and preserve aspect ratio m := resize.Resize(uint(w), uint(h), img, resize.Lanczos3) out, err := os.Create(fileSmall) if err != nil { return err } defer out.Close() // write new image to file return jpeg.Encode(out, m, nil) }
func ConvertMenuIcon(i image.Image) *BitmapImage { menubarHeigh := GetSystemMenuImageSize() c := resize.Resize(menubarHeigh, menubarHeigh, i, resize.Lanczos3) return BitmapImageNew(c) }
func renderThumbs() { images, err := ioutil.ReadDir("src/assets/photos") if err != nil { log.Printf("Error: %v\n", err.Error()) return } for _, img := range images { if !img.IsDir() { f, err := os.Open(fmt.Sprintf("src/assets/photos/%v", img.Name())) if err != nil { log.Printf("Error: %v\n", err.Error()) } else { i, err := jpeg.Decode(f) if err != nil { log.Printf("Error: %v\n", err.Error()) } else { f.Close() thumb := resize.Resize(400, 0, i, resize.Lanczos3) out, err := os.Create(fmt.Sprintf("src/assets/photos/thumbs/%v", img.Name())) if err != nil { log.Printf("Error: %v\n", err.Error()) } else { defer out.Close() jpeg.Encode(out, thumb, nil) } } } } } }
func (r *ResizeConverter) Convert(inFile string, outFile string, rect Rect) error { in, err := os.Open(inFile) if err != nil { log.Fatalf("Runner(File): cannot open source file '%s' for reading (%s).", inFile, err) } defer in.Close() out, err := os.Create(outFile) if err != nil { log.Printf("ERROR: cannot create new file %s (%s)", outFile, err) } defer out.Close() source, _, err := image.Decode(in) if err != nil { return err } interp, ok := interpolations[r.Interpolation] if !ok { interp = interpolations["l3"] } resized := resize.Resize(rect.Width, rect.Height, source, interp) png.Encode(out, resized) return nil }
func NewThumbnail(uri string, width, height uint) (filepath, mediatype string, w, h int, err error) { fp, mediatype, _, err := document.DefaultCurl().Download(uri) if err != nil { return } f, err := os.Open(fp) if err != nil { return } defer f.Close() img, mediatype, err := image.Decode(f) if err != nil { return } imgnew := resize.Resize(width, height, img, resize.MitchellNetravali) w = imgnew.Bounds().Max.X h = imgnew.Bounds().Max.Y of, err := ioutil.TempFile("", "") if err != nil { return } defer of.Close() err = jpeg.Encode(of, imgnew, &jpeg.Options{90}) if err != nil { return } filepath = of.Name() return }
func writeAnsiImage(img image.Image, file *os.File, width int) { m := resize.Resize(uint(width), uint(float32(width)*PROPORTION), img, resize.Lanczos3) var current, previous string bounds := m.Bounds() for y := bounds.Min.Y; y < bounds.Max.Y; y++ { for x := bounds.Min.X; x < bounds.Max.X; x++ { current = toAnsiCode(m.At(x, y)) if current != previous { fmt.Print(current) file.WriteString(current) } if ANSI_RESET != current { char := string(CHARACTERS[rand.Int()%len(CHARACTERS)]) fmt.Print(char) file.WriteString(char) } else { fmt.Print(" ") file.WriteString(" ") } } fmt.Print("\n") file.WriteString("\n") } fmt.Print(ANSI_RESET) file.WriteString(ANSI_RESET) }
// Generates a resized image image from the original. func (s *Store) generate(name, size, interp string) (path string, err error) { uSize, err := strconv.ParseUint(size, 10, 0) if err != nil { return } interpolation, ok := interpolations[interp] if !ok { return "", errors.New("Unknown interpolation: " + interp) } f, err := os.Open(s.hashedPath(name, "orig")) if err != nil { return } defer f.Close() img, _, err := image.Decode(f) if err != nil { return } newImg := resize.Resize(uint(uSize), 0, img, interpolation) return s.store(filepath.Join(size, interp), name, newImg) }
//截图生成文件 func resizeImage2file(src_img, dest_img string) { file, err := os.Open(src_img) if err != nil { fmt.Println(err) return } // decode jpeg into image.Image img, err := jpeg.Decode(file) if err != nil { fmt.Println(err) return } file.Close() m := resize.Resize(0, 1000, img, resize.Lanczos2) out, err := os.Create(dest_img) if err != nil { fmt.Println(err) return } defer out.Close() err = jpeg.Encode(out, m, nil) if err != nil { fmt.Println(err) return } }
func imgToFile(ic *iconf) (string, error) { img := resize.Resize(ic.width, 0, ic.image, resize.NearestNeighbor) ic.height = uint(img.Bounds().Size().Y) ic.fid = fmt.Sprintf("%s-%s-%s-%s-%s-%s-%d-%d", ic.machine, ic.format, ic.density, ic.ui, ic.hash, ic.color, ic.width, ic.height) dir := fmt.Sprintf("%s/%s/%s/%s/%s/%s/%s", conf.SushiobrolStore, ic.machine, ic.format, ic.density, ic.ui, ic.hash[0:2], ic.hash[2:4]) ic.path = fmt.Sprintf("%s/%s", dir, ic.fid) out, err := os.Create(ic.path) if err != nil { log.Println(err) return "", err } defer out.Close() if conf.InputType == "jpeg" { err = jpeg.Encode(out, img, nil) // write image to file if err != nil { fmt.Println("ERROR: Unable to Encode into webp") return "", err } } else { if webp.Encode(out, img, &webp.Options{conf.Lossless, conf.Quality}); err != nil { fmt.Println("ERROR: Unable to Encode into webp") return "", err } } return ic.fid, err }
// Resize all images given to it func resizeImages(path string, dim *Dimensions, progress chan int) { file, err := os.Open(path) if err != nil { log.Fatal(err) progress <- 1 return } img, err := jpeg.Decode(file) file.Close() if err != nil { log.Fatal(err) progress <- 1 return } res := resize.Resize(dim.height, dim.width, img, resize.Lanczos3) out, err := os.Create(PutImagePath + strconv.FormatInt(rand.Int63(), 36) + ".jpg") if err != nil { log.Fatal(err) progress <- 1 return } defer out.Close() jpeg.Encode(out, res, nil) progress <- 1 }
func ResizeImage(src, dst string) (err error) { // open "test.jpg" file, err := os.Open(src) if err != nil { // mlog.Error(err) return err } defer file.Close() // decode jpeg into image.Image img, err := jpeg.Decode(file) if err != nil { // mlog.Error(err) return err } // file.Close() // resize to width 1000 using Lanczos resampling // and preserve aspect ratio m := resize.Resize(80, 0, img, resize.Lanczos3) out, err := os.Create(dst) if err != nil { // mlog.Error(err) return err } defer out.Close() // write new image to file return jpeg.Encode(out, m, nil) }
func createIconButton(driver gxui.Driver, theme gxui.Theme, iconPath string) gxui.Button { button := theme.CreateButton() button.SetType(gxui.PushButton) fileBytes, err := assets.Asset(iconPath) if err != nil { log.Printf("Error: Failed to read asset %s: %s", iconPath, err) return button } f := bytes.NewBuffer(fileBytes) src, _, err := image.Decode(f) if err != nil { log.Printf("Error: Failed to decode image %s: %s", iconPath, err) return button } src = resize.Resize(24, 24, src, resize.Bilinear) rgba := image.NewRGBA(src.Bounds()) draw.Draw(rgba, src.Bounds(), src, image.ZP, draw.Src) texture := driver.CreateTexture(rgba, 1) icon := theme.CreateImage() icon.SetTexture(texture) button.AddChild(icon) return button }
// DifferenceHash computes the difference hash of an image. func DifferenceHash(source image.Image) uint64 { const sw, sh, hw, hh = 9, 8, 8, 8 // Convert the image to the grayscale colourspace. bounds := source.Bounds() width, height := bounds.Max.X, bounds.Max.Y gray := image.NewGray(source.Bounds()) for x := 0; x < width; x++ { for y := 0; y < height; y++ { gray.Set(x, y, source.At(x, y)) } } // Resize the image. shrunk := resize.Resize(sw, sh, gray, resize.NearestNeighbor).(*image.Gray) // Compute the difference hash. var hash uint64 for y := 0; y < hh; y++ { for x := 0; x < hw; x++ { if shrunk.GrayAt(x, y).Y < shrunk.GrayAt(x+1, y).Y { hash |= 1 << uint64((y*hw)+x) } } } return hash }
func (c *appContext) uploadPic(a *multipart.FileHeader) (string, string) { log.Println("In upload pic territory") bucket := c.bucket file, err := a.Open() defer file.Close() if err != nil { panic(err.Error()) } if err != nil { panic(err) } buf, _ := ioutil.ReadAll(file) fn := uuid.New() fname := "places/" + fn + path.Ext(a.Filename) thumbname := "placesthumb/" + fn + path.Ext(a.Filename) log.Println(fname) b := "http://s3-us-west-2.amazonaws.com/" + c.bucket.Name + "/" + fname d := "http://s3-us-west-2.amazonaws.com/" + c.bucket.Name + "/" + thumbname filetype := http.DetectContentType(buf) err = bucket.Put(fname, buf, filetype, s3.PublicRead) if err != nil { log.Println("bucket put error for main image") panic(err.Error()) } log.Print("added a full image") img, err := jpeg.Decode(bytes.NewReader(buf)) if err != nil { log.Println(err.Error()) } m := resize.Resize(200, 200, img, resize.Lanczos2) buf2 := new(bytes.Buffer) err = jpeg.Encode(buf2, m, nil) if err != nil { fmt.Println(err.Error()) } thumb := buf2.Bytes() filetype2 := http.DetectContentType(thumb) err = bucket.Put(thumbname, thumb, filetype2, s3.PublicRead) if err != nil { log.Println("bucket put error for thumbnail") panic(err.Error()) } log.Println("uploaded one thumb image") return b, d }
func (converter *ImageConverter) convertToType(path string, newType string, channel chan int) { file, _ := os.Open(path) pathParts := strings.Split(path, "/") filename := pathParts[len(pathParts)-1] picture, format, _ := image.Decode(file) rectangle := picture.Bounds() modifier := converter.widthModifier(newType) newWidth := uint(modifier * float32(rectangle.Dx())) if newWidth < 1 { newWidth = 1 } newImage := resize.Resize(newWidth, 0, picture, resize.NearestNeighbor) typeDirectory := strings.Join([]string{converter.Directory, "..", newType}, "/") os.Mkdir(typeDirectory, 0700) newFile, _ := os.Create(strings.Join([]string{typeDirectory, filename}, "/")) switch format { case "jpeg": jpeg.Encode(newFile, newImage, nil) case "png": png.Encode(newFile, newImage) } file.Close() newFile.Close() channel <- 1 }
func main() { // open "1.jpg" file, err := os.Open("3.jpg") if err != nil { log.Fatal(err) } // decode jpeg into image.Image img, err := jpeg.Decode(file) if err != nil { log.Fatal(err) } file.Close() // resize to width 1000 using Lanczos resampling // and preserve aspect ratio m := resize.Resize(1, 0, img, resize.NearestNeighbor) r, g, b, _ := m.At(0, 0).RGBA() fmt.Printf("%X%X%X", r>>8, g>>8, b>>8) // removing 1 byte 9A16->9A out, err := os.Create("test_resized3.jpg") if err != nil { log.Fatal(err) } defer out.Close() // write new image to file jpeg.Encode(out, m, nil) }
func thumb() image.Image { imageName := "test.jpg" imageFile, err := os.Open(imageName) if err != nil { log.Fatal(err) } var myImage *image.Image switch strings.ToLower(path.Ext(imageName)) { case ".jpg", ".jpeg": img, err := jpeg.Decode(imageFile) if err != nil { log.Fatal(err) } myImage = &img case ".png": img, err := png.Decode(imageFile) if err != nil { log.Fatal(err) } myImage = &img } imageFile.Close() m := resize.Resize(0, 200, *myImage, resize.MitchellNetravali) return m }
func MakeThumb(r io.Reader, w, h int, orient int) ([]byte, error) { img, _, err := image.Decode(r) if err != nil { return nil, err } m := resize.Resize(uint(w), uint(h), img, resize.Bicubic) switch orient { case 3, 4: m = imaging.Rotate180(m) case 5, 6: m = imaging.Rotate270(m) case 7, 8: m = imaging.Rotate90(m) } switch orient { case 2, 5, 4, 7: m = imaging.FlipH(m) } var buf bytes.Buffer err = jpeg.Encode(&buf, m, nil) if err != nil { return nil, err } return buf.Bytes(), nil }
// UploadAvatar saves custom avatar for user. // FIXME: split uploads to different subdirs in case we have massive users. func (u *User) UploadAvatar(data []byte) error { u.UseCustomAvatar = true img, _, err := image.Decode(bytes.NewReader(data)) if err != nil { return err } m := resize.Resize(234, 234, img, resize.NearestNeighbor) sess := x.NewSession() defer sess.Close() if err = sess.Begin(); err != nil { return err } if _, err = sess.Id(u.Id).AllCols().Update(u); err != nil { sess.Rollback() return err } os.MkdirAll(setting.AvatarUploadPath, os.ModePerm) fw, err := os.Create(u.CustomAvatarPath()) if err != nil { sess.Rollback() return err } defer fw.Close() if err = jpeg.Encode(fw, m, nil); err != nil { sess.Rollback() return err } return sess.Commit() }
func convertTrayIcon(i image.Image) NSImage { menubarHeight := uint(22) // FontHeight(NSFontMenuBarFontOfSize(0)) c := resize.Resize(menubarHeight, menubarHeight, i, resize.Lanczos3) return NSImageImage(c) }
// UploadAvatar saves custom avatar for user. // FIXME: split uploads to different subdirs in case we have massive users. func (u *User) UploadAvatar(data []byte) error { img, _, err := image.Decode(bytes.NewReader(data)) if err != nil { return fmt.Errorf("Decode: %v", err) } m := resize.Resize(290, 290, img, resize.NearestNeighbor) sess := x.NewSession() defer sessionRelease(sess) if err = sess.Begin(); err != nil { return err } u.UseCustomAvatar = true if err = updateUser(sess, u); err != nil { return fmt.Errorf("updateUser: %v", err) } os.MkdirAll(setting.AvatarUploadPath, os.ModePerm) fw, err := os.Create(u.CustomAvatarPath()) if err != nil { return fmt.Errorf("Create: %v", err) } defer fw.Close() if err = png.Encode(fw, m); err != nil { return fmt.Errorf("Encode: %v", err) } return sess.Commit() }
func convertMenuIcon(i image.Image) NSImage { menubarHeight := FontHeight(NSFontMenuFontOfSize(0)) c := resize.Resize(menubarHeight, menubarHeight, i, resize.Lanczos3) return NSImageImage(c) }
// default image format: jpeg func (this *Avatar) Encode(wr io.Writer, size int) (err error) { var img image.Image decodeImageFile := func(file string) (img image.Image, err error) { fd, err := os.Open(file) if err != nil { return } defer fd.Close() if img, err = jpeg.Decode(fd); err != nil { fd.Seek(0, os.SEEK_SET) img, err = png.Decode(fd) } return } imgPath := this.imagePath if !this.HasCache() { if this.AlterImage == "" { return errors.New("request image failed, and no alt image offered") } imgPath = this.AlterImage } if img, err = decodeImageFile(imgPath); err != nil { return } m := resize.Resize(uint(size), 0, img, resize.NearestNeighbor) return jpeg.Encode(wr, m, nil) }
func generateThumbnails(file multipart.File, userId, pathPrefix string, bucket *s3.Bucket) error { file.Seek(0, 0) img, _, err := image.Decode(file) if err != nil { log.Println("Error decoding image", err) return err } var buf bytes.Buffer for _, i := range THUMBNAIL_SIZES { resized := resize.Resize(uint(i), 0, img, resize.Lanczos3) err = jpeg.Encode(&buf, resized, nil) if err != nil { return err } path := fmt.Sprintf("%s/%d.jpg", pathPrefix, i) err = bucket.Put(path, buf.Bytes(), "image/jpeg", s3.PublicRead) if err != nil { return err } buf.Reset() } return err }