Exemple #1
0
func cropAndScale(avatar *Avatar) error {
	img, format, err := avatar2Image(avatar)
	if err != nil {
		return err
	}
	x := img.Bounds().Dx()
	y := img.Bounds().Dy()
	size := min(x, y)
	if x != y {
		log.Printf("Cropping img from %vx%v to %vx%v", x, y, size, size)
		img, err = cutter.Crop(img, cutter.Config{
			Width:  size,
			Height: size,
			Mode:   cutter.Centered})
		if err != nil {
			return err
		}
	}
	if size <= maxSize {
		return nil
	}
	log.Printf("Resizing img from %vx%v to %vx%v", size, size, maxSize, maxSize)
	resized := resize.Resize(uint(maxSize), uint(maxSize), img, resize.Bicubic)
	image2Avatar(avatar, resized, format)
	return nil
}
Exemple #2
0
// Crop
// Crops an image based on the given dimensions
func (cropper *CropService) Crop(height, width uint, image image.Image, ext string) ([]byte, error) {

	// Crop image
	file, err := cutter.Crop(image, cutter.Config{
		Width:   int(width),
		Height:  int(height),
		Options: cutter.Copy,
	})

	if err != nil {
		return nil, err
	}

	return cropper.decoder.EncodeImage(file, ext)
}
// read, resize, crop and zip a 'screenshot' named 'name' into 'zipArchive'
func convert(zipFile *zip.Writer, infile io.Reader, filename string) error {
	img, err := png.Decode(infile)
	if err != nil {
		return err
	}

	resized := resize.Resize(0, TargetHeight, img, resize.Bicubic)
	croppedImg, _ := cutter.Crop(resized, cutter.Config{
		Width:  TargetWidth,
		Height: TargetHeight,
		Mode:   cutter.Centered,
	})

	zippedFile, err := zipFile.Create(filename)
	if err != nil {
		return err
	}

	return jpeg.Encode(zippedFile, croppedImg, JpegQuality)
}
Exemple #4
0
func CropImg(srcImg image.Image, dstWidth, dstHeight int) image.Image {
	origBounds := srcImg.Bounds()
	origWidth := origBounds.Dx()
	origHeight := origBounds.Dy()

	dstImg, err := cutter.Crop(srcImg, cutter.Config{
		Height: dstHeight,      // height in pixel or Y ratio(see Ratio Option below)
		Width:  dstWidth,       // width in pixel or X ratio
		Mode:   cutter.TopLeft, // Accepted Mode: TopLeft, Centered
		Anchor: image.Point{
			origWidth / 12,
			origHeight / 8}, // Position of the top left point
		Options: 0, // Accepted Option: Ratio
	})
	if err != nil {
		Logln("[GIN] Cannot crop image:" + err.Error())
		return srcImg
	}
	return dstImg
}
Exemple #5
0
/*
Crop() takes in four parameters:

imageData : byte[] representing the input image

cWidth    : An int specifying the desired width of the cropped image

cHeight   : An int specifying the desired height of the cropped image

w         : An io.Writer to which to write the encoded ropped image bytes to
*/
func Crop(imageData []byte, cWidth int, cHeight int, w io.Writer) {

	imageType := http.DetectContentType(imageData)

	// Check if we can handle this image
	if !validateImageType(imageType) {
		panic("Cannot handle image of this type")
	}

	// We first decode the image
	reader := bytes.NewReader(imageData)
	img, _, err := image.Decode(reader)
	if err != nil {
		panic(err)
	}

	// Perform the cropping
	croppedImg, err := cutter.Crop(img, cutter.Config{
		Height:  cHeight,
		Width:   cWidth,
		Mode:    cutter.TopLeft,
		Anchor:  image.Point{60, 10},
		Options: 0,
	})

	if err != nil {
		panic(err)
	}

	// Now we encode the cropped image data using the appropriate
	// encoder and save it to the above file
	switch imageType {
	case "image/png":
		err = png.Encode(w, croppedImg)
	case "image/jpeg":
		err = jpeg.Encode(w, croppedImg, &jpeg.Options{})
	}
	if err != nil {
		panic(err)
	}
}
Exemple #6
0
func main() {
	var imageURL string
	flag.StringVar(&imageURL, "image", "", "")
	flag.Parse()

	if imageURL == "" {
		imageURL = "http://pics.dmm.co.jp/digital/pcgame/guide/selen_0024/head.jpg"
	}

	resp, err := http.Get(imageURL)
	if err != nil {
		log.Fatalln(err)
	}

	log.Println(resp.Header.Get("Content-Type"))

	img, err := jpeg.Decode(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	resp.Body.Close()

	{
		m := resize.Resize(300, 300, img, resize.Bicubic)

		out, err := os.Create("resize.jpg")
		if err != nil {
			log.Fatal(err)
		}
		defer out.Close()

		// write new image to file
		jpeg.Encode(out, m, nil)
	}

	{
		m := resize.Resize(300, 0, img, resize.Bicubic)

		out, err := os.Create("resize_width.jpg")
		if err != nil {
			log.Fatal(err)
		}
		defer out.Close()

		// write new image to file
		jpeg.Encode(out, m, nil)
	}

	{
		m := resize.Resize(0, 300, img, resize.Bicubic)

		out, err := os.Create("resize_height.jpg")
		if err != nil {
			log.Fatal(err)
		}
		defer out.Close()

		// write new image to file
		jpeg.Encode(out, m, nil)
	}

	{
		m := resize.Thumbnail(300, 300, img, resize.Bicubic)
		out, err := os.Create("thumbnail.jpg")
		if err != nil {
			log.Fatal(err)
		}
		defer out.Close()

		// write new image to file
		jpeg.Encode(out, m, nil)
	}

	{
		m, err := cutter.Crop(img, cutter.Config{
			Width:  300,
			Height: 300,
			Anchor: image.Point{0, 0},
			Mode:   cutter.Centered, // optional, default value
		})
		out, err := os.Create("crop_centered.jpg")
		if err != nil {
			log.Fatal(err)
		}
		defer out.Close()

		// write new image to file
		jpeg.Encode(out, m, nil)
	}

	{
		x, y := uint(640), uint(640)
		if img.Bounds().Size().X < img.Bounds().Size().Y {
			y = 0
		} else {
			x = 0
		}
		m, err := cutter.Crop(resize.Resize(x, y, img, resize.Bicubic), cutter.Config{
			Width:  640,
			Height: 640,
			Anchor: image.Point{0, 0},
			Mode:   cutter.Centered, // optional, default value
		})
		out, err := os.Create("resize_crop_centered.jpg")
		if err != nil {
			log.Fatal(err)
		}
		defer out.Close()

		// write new image to file
		jpeg.Encode(out, m, nil)
	}
}
Exemple #7
0
func SaveImage(file io.Reader) (*Image, error) {
	log.Println("Starting SaveImage")

	imageId := uniuri.NewLen(20)
	i, err := db.Get(Image{}, imageId)
	for err == nil && i != nil {
		// Shit, we generated an existing ImageId!
		// Aren't we so lucky?!
		imageId := uniuri.NewLen(20)
		i, err = db.Get(Image{}, imageId)
	}

	if err != nil {
		return nil, err
	}

	// Lets decode our image to work with it
	originalImg, _, err := image.Decode(file)
	if err != nil {
		return nil, err
	}

	originalWidht := originalImg.Bounds().Dx()
	originalHeight := originalImg.Bounds().Dy()
	maxSize := ""

	log.Printf("\nPreparing to save de image %dx%d\n", originalWidht, originalHeight)

	// We will save 3 resized images
	sizes := [...]string{"small", "medium", "large"}
	dimensions := [...]dimension{{261, 142}, {358, 194}, {748, 408}}

	// We will save the Thumbnails just if the original image
	// dimension is bigger or equals than the thumbnail dimension
	// to large thumbnail images
	for index, size := range sizes {
		newWidth := dimensions[index].Width
		newHeight := dimensions[index].Height
		widthRatio := float32(originalWidht) / float32(newWidth)    // Width ratio
		heightRatio := float32(originalHeight) / float32(newHeight) // Height ratio

		log.Printf("Trying to save img size %d, widthRatio: %f, heightRatio: %f\n", size, widthRatio, heightRatio)

		// We will resize and crop images small and medium and
		// just images bigger than large size will be saved with large scale
		if size == "small" || (widthRatio >= 1 && heightRatio >= 1) {
			maxSize = size
			// Below the values to the image be resized after be cropped
			// If resized width or height == 0, so the proportion will be conserved
			resizedWidth := 0  // Width to image be resized
			resizedHeight := 0 // Height to image be resized
			if widthRatio >= heightRatio {
				// We will resize based on height and crop it after resized
				resizedHeight = newHeight
			} else {
				// We will resize besed on height and crop it after resized
				resizedWidth = newWidth
			}

			fo, err := os.Create("public/img/" + imageId + "-" + size + ".png")
			if err != nil {
				return nil, err
			}

			// close fo on exit and check for its returned error
			defer func() {
				if err := fo.Close(); err != nil {
					panic(err)
				}
			}()

			// If the image is bigger in both directions
			if widthRatio >= 1 && heightRatio >= 1 {
				// Downscales an image preserving its aspect ratio to the maximum dimensions
				resizedImage := resize.Resize(uint(resizedWidth), uint(resizedHeight), originalImg, resize.Lanczos3)

				// If image still bigger, lets crop it to the right size
				croppedImg, err := cutter.Crop(resizedImage, cutter.Config{
					Width:  newWidth,
					Height: newHeight,
					Mode:   cutter.Centered,
				})
				if err != nil {
					return nil, err
				}

				png.Encode(fo, croppedImg)

			} else {
				// If the image isn't bigger in both directions
				// We will enter here just if its the small/medium size image

				if originalHeight < newHeight {
					// If this image isn't taller enought
					newHeight = originalHeight
				}
				if originalWidht < newWidth {
					// If this image isn't large enought
					newWidth = originalWidht
				}
				// If image still bigger, lets crop it to the right size
				croppedImg, err := cutter.Crop(originalImg, cutter.Config{
					Width:  newWidth,
					Height: newHeight,
					Mode:   cutter.Centered,
				})
				if err != nil {
					return nil, err
				}

				png.Encode(fo, croppedImg)
			}

			log.Printf("Saving the image size %s\n", size)
		}
	}

	if maxSize == "" {
		// There is no image saved, cause the original image is so small
		return nil, nil
	}

	image := &Image{
		ImageId:  imageId,
		MaxSize:  maxSize,
		Creation: time.Now(),
		Deleted:  false,
	}

	err = db.Insert(image)
	if err != nil {
		return nil, err
	}

	return image, nil

}
Exemple #8
0
// generate one thumbnail
func generateThumbnail(image_file string, overwrite bool) error {
	var err error
	if IsDirectory(thumbs_path) {
		source_image := folder_path + "/" + image_file

		mime, err := getContentType(source_image)
		if err != nil {
			return err
		}

		for thumb_folder, thumb_size := range thumb_sizes {
			thumb_folder_path := thumbs_path + "/" + thumb_folder
			if !Exists(thumb_folder_path) {
				log.Println("Creating folder" + thumb_folder_path)
				err := os.Mkdir(thumb_folder_path, 0755)
				if err != nil {
					return err
				}
			}

			if IsDirectory(thumb_folder_path) {
				thumb_file_path := thumb_folder_path + "/" + image_file

				width, height, exact_size, err := parseSize(thumb_size)
				if err != nil {
					return err
				}

				if Exists(thumb_file_path) && overwrite == false {
					log.Printf("Nothing to do, thumb %s already exists\n", thumb_file_path)
				} else {
					var img image.Image

					file, err := os.Open(source_image)
					if err != nil {
						return err
					}

					if mime == "image/jpeg" {
						img, err = jpeg.Decode(file)
						if err != nil {
							return err
						}
					} else if mime == "image/gif" {
						img, err = gif.Decode(file)
						if err != nil {
							return err
						}
					} else if mime == "image/png" {
						img, err = png.Decode(file)
						if err != nil {
							return err
						}
					}

					file.Close()

					var resized_image image.Image

					if exact_size {
						img_width, img_height, err := getImageDimensions(source_image)
						if err != nil {
							return err
						}

						img_ratio := float64(img_width) / float64(img_height)

						thumb_ratio := float64(width) / float64(height)

						resize_width := uint(width)
						resize_height := uint(height)

						if img_ratio > thumb_ratio {
							resize_width = uint(img_width * 5)
						} else {
							resize_height = uint(img_height * 5)
						}

						image := resize.Thumbnail(resize_width, resize_height, img, resize.Lanczos3)

						resized_image, err = cutter.Crop(image, cutter.Config{
							Width:  width,
							Height: height,
						})
						if err != nil {
							return err
						}

					} else {
						resized_image = resize.Thumbnail(uint(width), uint(height), img, resize.Lanczos3)
					}

					out, err := os.Create(thumb_file_path)
					if err != nil {
						return err
					}

					defer out.Close()

					if mime == "image/jpeg" {
						var jpeg_opt jpeg.Options
						jpeg_opt.Quality = viper.GetInt("jpeg_quality")
						jpeg.Encode(out, resized_image, &jpeg_opt)
					} else if mime == "image/gif" {
						var gif_opt gif.Options
						gif_opt.NumColors = 256

						gif.Encode(out, resized_image, &gif_opt)
					} else if mime == "image/png" {
						png.Encode(out, resized_image)
					}
				}
			} else {
				return errors.New("Can't create thumbnails. " + thumb_folder_path + " must be a directory")
			}
		}
	} else {
		return errors.New("Thumbs folder doesn't exist or is not a Folder")
	}

	return err
}
Exemple #9
0
func resize_picture(filename, output_folder string) {

	file_temp := strings.Split(filename, "/")
	img_name := file_temp[len(file_temp)-1]

	output_file := output_folder + img_name
	output_thumb := output_folder + strings.Split(img_name, ".")[0] + "_thumb.jpg"

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

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

	file.Close()

	b := img.Bounds()
	imgWidth := b.Max.X
	imgHeight := b.Max.Y

	if imgWidth > 1000 {
		// resize to width 1000 using Lanczos resampling
		// and preserve aspect ratio
		m := resize.Resize(1000, 0, img, resize.Lanczos3)

		out, err := os.Create(output_file)
		if err != nil {
			log.Fatal(err)
		}
		defer out.Close()

		jpeg.Encode(out, m, nil)
	}

	// Create the thumbnails
	n := img

	switch {
	case imgHeight <= 275:
		n, err = cutter.Crop(img, cutter.Config{
			Width:  350,
			Height: 275,
			Mode:   cutter.Centered,
		})
	default:
		tempn := resize.Resize(350, 0, img, resize.Lanczos3)
		n, err = cutter.Crop(tempn, cutter.Config{
			Width:  350,
			Height: 275,
			Mode:   cutter.Centered,
		})
	}

	out2, err := os.Create(output_thumb)
	if err != nil {
		log.Fatal(err)
	}
	defer out2.Close()

	// write resized image and thumbnails to file

	jpeg.Encode(out2, n, nil)
}
Exemple #10
0
func (m *markedImage) Transform(crop image.Rectangle, width, height uint, dontenlarge bool, format string, resample resize.InterpolationFunction) (Image, error) {
	novaFoto, err := m.Copy()
	if err != nil {
		return nil, e.Forward(err)
	}

	img, err := novaFoto.Image()
	if err != nil {
		return nil, e.Forward(err)
	}

	if width > math.MaxInt32 {
		return nil, e.New("width is big")
	}
	if height > math.MaxInt32 {
		return nil, e.New("height is big")
	}

	bounds, err := m.Bounds()
	if err != nil {
		return nil, e.Forward(err)
	}
	w := bounds.Dx()
	h := bounds.Dy()

	f, err := m.Format()
	if err != nil {
		return nil, e.Forward(err)
	}

	if crop.Empty() && ((width == 0 && height == 0) || (int(width) == w && int(height) == h)) && (format == "" || format == f) {
		return novaFoto, nil
	}

	if !crop.Empty() {
		sub, ok := img.(SubImager)
		if !ok {
			return nil, e.New("this image type don't support cropping")
		}
		img = sub.SubImage(crop)
	}

	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)

		imgRatio := img
		if width > 0 && height > 0 {
			ratio := round.RoundDec32(float32(w)/float32(h), 1)
			newRatio := round.RoundDec32(float32(width)/float32(height), 1)

			if ratio != newRatio {
				//TODO: se imagem tem largura menor que 10px não vai funcionar
				imgRatio, err = cutter.Crop(img, cutter.Config{
					Width:   int(newRatio * 10.0),
					Height:  10,
					Mode:    cutter.Centered,
					Options: cutter.Ratio,
				})
				if err != nil {
					return nil, e.Push(err, "can't crop the image")
				}
				rect = imgRatio.Bounds()
				w = uint(rect.Max.X - rect.Min.X)
				h = uint(rect.Max.Y - rect.Min.Y)
			}
		}

		imgResized = imgRatio
		if (width >= w || height >= h) && !dontenlarge {
			imgResized = resize.Resize(width, height, imgRatio, resample)
		} else if width < w && height < h {
			imgResized = resize.Resize(width, height, imgRatio, resample)
		}
	}

	// rect := imgResized.Bounds()
	// novaFoto.Width_ = rect.Max.X - rect.Min.X
	// novaFoto.Height_ = rect.Max.Y - rect.Min.Y

	b := make([]byte, 0, 1024*1024*5)
	buf := bytes.NewBuffer(b)

	// if format == "" {
	// 	format = novaFoto.Mime_
	// }

	switch format {
	// case "image/bmp", "image/x-windows-bmp":
	// 	err := bmp.Encode(buf, imgResized)
	// 	if err != nil {
	// 		return nil, e.Forward(err)
	// 	}
	// 	novaFoto.Format_ = "bmp"
	// case "image/gif":
	// 	opt := &gif.Options{
	// 		NumColors: 256,
	// 	}
	// 	err := gif.Encode(buf, imgResized, opt)
	// 	if err != nil {
	// 		return nil, e.Forward(err)
	// 	}
	// 	novaFoto.Format_ = "gif"
	case "image/jpeg":
		opt := &jpeg.Options{
			Quality: Quality,
		}
		err := jpeg.Encode(buf, imgResized, opt)
		if err != nil {
			return nil, e.Forward(err)
		}
		//novaFoto.Format_ = "jpeg"
	// case "image/png":
	// 	err := png.Encode(buf, imgResized)
	// 	if err != nil {
	// 		return nil, e.Forward(err)
	// 	}
	// 	novaFoto.Format_ = "png"
	// case "image/tiff", "image/x-tiff":
	// 	opt := &tiff.Options{
	// 		Compression: tiff.Deflate,
	// 		Predictor:   true,
	// 	}
	// 	err := tiff.Encode(buf, imgResized, opt)
	// 	if err != nil {
	// 		return nil, e.Forward(err)
	// 	}
	// 	novaFoto.Format_ = "tiff"
	default:
		return nil, e.New("image format isn't supported")
	}

	// novaFoto.Mime_ = format
	// novaFoto.FileSize_ = int64(buf.Len())
	// novaFoto.Data = buf.Bytes()

	return novaFoto, nil
}