Ejemplo n.º 1
0
// GenerateThumbnail assumes that the images have already been saved to storage,
// and that one or more image is contained within imagesValue. Returns the
// resulting filename of the generated thumbnail if successful, or an error
// otherwise.
func (imagesValue *ImagesValue) GenerateThumbnail() (string, error) {
	if !imagesValue.IsComplete() {
		return "", errors.New("No images to generate thumbnail for.")
	}
	filename := MediaDir + ThumbnailDir + uuid.NewUUID().String() + ThumbnailType
	mw := imagick.NewMagickWand()
	defer mw.Destroy()
	err := mw.ReadImage(fieldsConfig.Website.Directory + (*imagesValue)[0])
	if err != nil {
		return "", err
	}

	err = mw.ThumbnailImage(ThumbnailMaxWidth, ThumbnailMaxHeight)
	if err != nil {
		return "", err
	}

	err = mw.SetImageCompressionQuality(ThumbnailQuality)
	if err != nil {
		return "", err
	}

	err = mw.WriteImage(fieldsConfig.Website.Directory + filename)
	if err != nil {
		return "", err
	}

	return filename, nil
}
Ejemplo n.º 2
0
// SaveImage converts the given base64 string into an image, saves it to the
// file system, and returns its filename. If it is unsuccessful, an error is
// returned.
func SaveImage(base64str string) (string, error) {
	// removes header information
	strs := strings.Split(base64str, ",")
	str := strs[len(strs)-1]

	blob, err := base64.StdEncoding.DecodeString(str)
	if err != nil {
		return "", err
	}
	filename := MediaDir + ImageDir + uuid.NewUUID().String() + ImageType

	mw := imagick.NewMagickWand()
	defer mw.Destroy()
	err = mw.ReadImageBlob(blob)
	if err != nil {
		return "", err
	}

	width := mw.GetImageWidth()
	newWidth := width
	height := mw.GetImageHeight()
	newHeight := height

	if width > ImageMaxWidth {
		newWidth = ImageMaxWidth
		newHeight = uint(float64(height) / float64(width/ImageMaxWidth))
	}
	if newHeight > ImageMaxHeight {
		newHeight = ImageMaxHeight
		newWidth = uint(float64(width) / float64(height/ImageMaxHeight))
	}

	// Resize the image using the Lanczos filter
	// The blur factor is a float, where > 1 is blurry, < 1 is sharp
	err = mw.ResizeImage(newWidth, newHeight, imagick.FILTER_LANCZOS, 1)
	if err != nil {
		return "", err
	}

	err = mw.SetImageCompressionQuality(ImageQuality)
	if err != nil {
		return "", err
	}

	err = mw.WriteImage(fieldsConfig.Website.Directory + filename)
	if err != nil {
		return "", err
	}

	return filename, nil
}