Exemplo n.º 1
13
//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
}
Exemplo n.º 2
5
//水印
func waterMark(picBytes []byte) []byte {
	// 打开水印图并解码
	img, fileType, _ := image.Decode(bytes.NewBuffer(picBytes))

	//读取水印图片
	watermark, _ := png.Decode(bytes.NewBuffer(wm))

	//原始图界限
	origin_size := img.Bounds()

	//创建新图层
	canvas := image.NewNRGBA(origin_size)

	//贴原始图
	draw.Draw(canvas, origin_size, img, image.ZP, draw.Src)
	//贴水印图
	draw.Draw(canvas, watermark.Bounds().Add(image.Pt(origin_size.Dx()-watermark.Bounds().Dx(), origin_size.Dy()-watermark.Bounds().Dy()-4)), watermark, image.ZP, draw.Over)

	//生成新图片
	buff := bytes.NewBuffer([]byte{})

	switch fileType {
	case "jpeg":
		jpeg.Encode(buff, canvas, &jpeg.Options{95})
	default:
		png.Encode(buff, canvas)
	}

	return buff.Bytes()
}
Exemplo n.º 3
1
func (h *ImgHandler) writeImage(w io.Writer, img image.Image, format string) (err error) {
	switch format {
	case "jpg", "jpeg":
		var rgba *image.RGBA
		if nrgba, ok := img.(*image.NRGBA); ok {
			if nrgba.Opaque() {
				rgba = &image.RGBA{
					Pix:    nrgba.Pix,
					Stride: nrgba.Stride,
					Rect:   nrgba.Rect,
				}
			}
		}
		if rgba != nil {
			err = jpeg.Encode(w, rgba, &jpeg.Options{Quality: 95})
		} else {
			err = jpeg.Encode(w, img, &jpeg.Options{Quality: 95})
		}
	case "png":
		err = png.Encode(w, img)
	default:
		err = fmt.Errorf("unknown format when writting %v", format)
	}
	return
}
Exemplo n.º 4
0
func resizeThumbnail(from *bytes.Buffer, spec *ThumbnailSpec) (to io.Reader, w int, h int, err error) {

	src, name, err := image.Decode(from)
	if err != nil {
		return
	}
	srcB := src.Bounds()

	w, h = spec.CalculateRect(srcB)

	rect := image.Rect(0, 0, srcB.Dx(), srcB.Dy())

	dst := resize.Resize(src, rect, w, h)

	var buf bytes.Buffer
	switch name {
	case "jpeg":
		jpeg.Encode(&buf, dst, &jpeg.Options{95})
	case "png":
		png.Encode(&buf, dst)
	case "gif":
		jpeg.Encode(&buf, dst, &jpeg.Options{95})
	}

	to = &buf
	return
}
Exemplo n.º 5
0
// 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
}
Exemplo n.º 6
0
func main() {
	m := martini.Classic()

	m.Get("/", func(res http.ResponseWriter, req *http.Request) {
		res.Header().Set("Content-Type", "image/jpeg")
		err := jpeg.Encode(res, thumb(), &jpeg.Options{75})
		if err != nil {
			res.WriteHeader(500)
		} else {
			res.WriteHeader(200)
		}
	})

	m.Get("/cached", func(response http.ResponseWriter, req *http.Request) {
		response.Header().Set("Content-Type", "image/jpeg")
		err := jpeg.Encode(response, preThumb(), &jpeg.Options{75})
		if err != nil {
			response.WriteHeader(500)
		} else {
			response.WriteHeader(200)
		}
	})

	log.Fatal(http.ListenAndServe(":10010", m))
	m.Run()
}
Exemplo n.º 7
0
// Encode writes the image img to w in the specified format (JPEG, PNG, GIF, TIFF or BMP).
func Encode(w io.Writer, img image.Image, format Format) error {
	var err error
	switch format {
	case JPEG:
		var rgba *image.RGBA
		if nrgba, ok := img.(*image.NRGBA); ok {
			if nrgba.Opaque() {
				rgba = &image.RGBA{
					Pix:    nrgba.Pix,
					Stride: nrgba.Stride,
					Rect:   nrgba.Rect,
				}
			}
		}
		if rgba != nil {
			err = jpeg.Encode(w, rgba, &jpeg.Options{Quality: 95})
		} else {
			err = jpeg.Encode(w, img, &jpeg.Options{Quality: 95})
		}

	case PNG:
		err = png.Encode(w, img)
	case GIF:
		err = gif.Encode(w, img, &gif.Options{NumColors: 256})
	case TIFF:
		err = tiff.Encode(w, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
	case BMP:
		err = bmp.Encode(w, img)
	default:
		err = ErrUnsupportedFormat
	}
	return err
}
Exemplo n.º 8
0
// makeTestImages generates an RGBA and a grayscale image and returns
// testImages containing the JPEG encoded form as bytes and the expected color
// model of the image when decoded.
func makeTestImages() ([]testImage, error) {
	var ims []testImage
	w := bytes.NewBuffer(nil)
	im1 := image.NewRGBA(image.Rect(0, 0, width, height))
	for i := range im1.Pix {
		switch {
		case i%4 == 3:
			im1.Pix[i] = 255
		default:
			im1.Pix[i] = uint8(i)
		}
	}
	if err := jpeg.Encode(w, im1, nil); err != nil {
		return nil, err
	}
	ims = append(ims, testImage{im: im1, buf: w.Bytes()})

	w = bytes.NewBuffer(nil)
	im2 := image.NewGray(image.Rect(0, 0, width, height))
	for i := range im2.Pix {
		im2.Pix[i] = uint8(i)
	}
	if err := jpeg.Encode(w, im2, nil); err != nil {
		return nil, err
	}
	ims = append(ims, testImage{im: im2, buf: w.Bytes()})
	return ims, nil

}
Exemplo n.º 9
0
func (handler *ImageUtilsHandler) Save(img image.Image, format string) ([]byte, error) {
	// Based on github.com/disintegration/imaging/helpers.go Save()
	var err error
	writer := new(bytes.Buffer)
	switch format {
	case ".jpg", ".jpeg":
		var rgba *image.RGBA
		if nrgba, ok := img.(*image.NRGBA); ok {
			if nrgba.Opaque() {
				rgba = &image.RGBA{
					Pix:    nrgba.Pix,
					Stride: nrgba.Stride,
					Rect:   nrgba.Rect,
				}
			}
		}
		if rgba != nil {
			err = jpeg.Encode(writer, rgba, &jpeg.Options{Quality: 95})
		} else {
			err = jpeg.Encode(writer, img, &jpeg.Options{Quality: 95})
		}

	case ".png":
		err = png.Encode(writer, img)
	case ".tif", ".tiff":
		err = tiff.Encode(writer, img, &tiff.Options{Compression: tiff.Deflate, Predictor: true})
	case ".bmp":
		err = bmp.Encode(writer, img)
	default:
		return nil, errors.New("Invalid image format")
	}

	return writer.Bytes(), err
}
Exemplo n.º 10
0
func HandleImage(f func(img image.Image, ctx *ProxyCtx) image.Image) RespHandler {
	return FuncRespHandler(func(resp *http.Response, ctx *ProxyCtx) *http.Response {
		if !RespIsImage.HandleResp(resp, ctx) {
			return resp
		}
		if resp.StatusCode != 200 {
			// we might get 304 - not modified response without data
			return resp
		}
		contentType := resp.Header.Get("Content-Type")

		const kb = 1024
		regret := regretable.NewRegretableReaderCloserSize(resp.Body, 16*kb)
		resp.Body = regret
		img, imgType, err := image.Decode(resp.Body)
		if err != nil {
			regret.Regret()
			ctx.Warnf("%s: %s", ctx.Req.Method+" "+ctx.Req.URL.String()+" Image from "+ctx.Req.RequestURI+"content type"+
				contentType+"cannot be decoded returning original image", err)
			return resp
		}
		result := f(img, ctx)
		buf := bytes.NewBuffer([]byte{})
		switch contentType {
		// No gif image encoder in go - convert to png
		case "image/gif", "image/png":
			if err := png.Encode(buf, result); err != nil {
				ctx.Warnf("Cannot encode image, returning orig %v %v", ctx.Req.URL.String(), err)
				return resp
			}
			resp.Header.Set("Content-Type", "image/png")
		case "image/jpeg", "image/pjpeg":
			if err := jpeg.Encode(buf, result, nil); err != nil {
				ctx.Warnf("Cannot encode image, returning orig %v %v", ctx.Req.URL.String(), err)
				return resp
			}
		case "application/octet-stream":
			switch imgType {
			case "jpeg":
				if err := jpeg.Encode(buf, result, nil); err != nil {
					ctx.Warnf("Cannot encode image as jpeg, returning orig %v %v", ctx.Req.URL.String(), err)
					return resp
				}
			case "png", "gif":
				if err := png.Encode(buf, result); err != nil {
					ctx.Warnf("Cannot encode image as png, returning orig %v %v", ctx.Req.URL.String(), err)
					return resp
				}
			}
		default:
			panic("unhandlable type" + contentType)
		}
		resp.Body = ioutil.NopCloser(buf)
		return resp
	})
}
Exemplo n.º 11
0
func resizeThumbnail(from *bytes.Buffer, spec *ThumbnailSpec) (to io.Reader, w int, h int, err error) {

	src, name, err := image.Decode(from)
	if err != nil {
		return
	}
	srcB := src.Bounds()

	var dst image.Image
	if spec.CropToSquare && srcB.Dx() != srcB.Dy() {
		var rect image.Rectangle
		if srcB.Dx() > srcB.Dy() {
			x1 := (srcB.Dx() - srcB.Dy()) / 2
			x2 := srcB.Dx() - x1
			rect = image.Rect(x1, 0, x2, srcB.Dy())

		} else {
			rect = image.Rect(0, 0, srcB.Dx(), srcB.Dx())
		}
		w = spec.Height
		if (spec.Height > spec.Width && spec.Width != 0) || spec.Height == 0 {
			w = spec.Width
		}
		h = w

		cropedImg := imaging.Crop(src, rect)
		rect = cropedImg.Bounds()
		dst = resize.Resize(cropedImg, rect, w, h)

	} else {
		w, h = spec.CalculateRect(srcB, spec.CropToSquare)

		if w >= srcB.Dx() || h >= srcB.Dy() {
			w, h = srcB.Dx(), srcB.Dy()
		}

		rect := image.Rect(0, 0, srcB.Dx(), srcB.Dy())
		dst = resize.Resize(src, rect, w, h)
	}

	var buf bytes.Buffer
	switch name {
	case "jpeg":
		jpeg.Encode(&buf, dst, &jpeg.Options{95})
	case "png":
		png.Encode(&buf, dst)
	case "gif":
		jpeg.Encode(&buf, dst, &jpeg.Options{95})
	case "bmp":
		jpeg.Encode(&buf, dst, &jpeg.Options{95})
	}

	to = &buf
	return
}
Exemplo n.º 12
0
func Encode(iw io.Writer, img image.Image, format string) {
	switch format {
	case "jpg":
		jpeg.Encode(iw, img, nil)
	case "jpeg":
		jpeg.Encode(iw, img, nil)
	case "png":
		png.Encode(iw, img)
	default:
		log.Fatal("Argument Error: available formats are jpg and png")
	}
}
Exemplo n.º 13
0
// handler serves a turkey snapshot for the given request.
func handler(w http.ResponseWriter, r *http.Request) {
	// Defer a function to recover from any panics.
	// When recovering from a panic, log the error condition to
	// the App Engine dashboard and send the default image to the user.
	defer func() {
		if err := recover(); err != nil {
			c := appengine.NewContext(r)
			c.Errorf("%s", err)
			c.Errorf("%s", "Traceback: "+r.RawURL)
			if defaultImage != nil {
				w.Header().Set("Content-type", "image/jpeg")
				jpeg.Encode(w, defaultImage, &imageQuality)
			}
		}
	}()

	// Load images from disk on the first request.
	loadOnce.Do(load)

	// Make a copy of the background to draw into.
	bgRect := backgroundImage.Bounds()
	m := image.NewRGBA(bgRect.Dx(), bgRect.Dy())
	draw.Draw(m, m.Bounds(), backgroundImage, image.ZP, draw.Over)

	// Process each character of the request string.
	code := strings.ToLower(r.URL.Path[len(prefix):])
	for i, p := range code {
		// Decode hex character p in place.
		if p < 'a' {
			// it's a digit
			p = p - '0'
		} else {
			// it's a letter
			p = p - 'a' + 10
		}

		t := urlMap[i]    // element type by index
		em := elements[t] // element images by type
		if p >= len(em) {
			panic(fmt.Sprintf("element index out of range %s: "+
				"%d >= %d", t, p, len(em)))
		}

		// Draw the element to m,
		// using the layoutMap to specify its position.
		draw.Draw(m, layoutMap[t], em[p], image.ZP, draw.Over)
	}

	// Encode JPEG image and write it as the response.
	w.Header().Set("Content-type", "image/jpeg")
	w.Header().Set("cache-control", "public, max-age=259200")
	jpeg.Encode(w, m, &imageQuality)
}
Exemplo n.º 14
0
func main() {
	flag.Parse()

	if len(flag.Args()) == 0 {
		flag.Usage()
		os.Exit(-1)
	}

	for _, input := range flag.Args() {
		f, err := os.Open(input)
		if err != nil {
			fmt.Printf("Failed to open %s, %v\n", input, err)
			os.Exit(-1)
		}

		img, format, err := image.Decode(f)
		if err != nil {
			fmt.Printf("Failed to decode %s, %v, %v\n", input, format, err)
			os.Exit(-1)
		}

		for threshold = *minThreshold; threshold < *maxThreshold; threshold += *thresholdInc {
			sortedImg := img
			for i := 0; i < *passes; i++ {
				sortedImg = pixelSort(sortedImg)
			}

			output := fmt.Sprintf("sorted_%dx_%fl_%s", *passes, threshold, input)
			if format == "gif" {
				output = fmt.Sprint(output[:3], "jpeg")
			}

			newFile, err := os.Create(output)
			if err != nil {
				fmt.Printf("Failed to write %s", output)
				os.Exit(-1)
			}

			switch format {
			case "jpeg":
				jpeg.Encode(newFile, sortedImg, nil)
			case "png":
				png.Encode(newFile, sortedImg)
			case "gif":
				jpeg.Encode(newFile, sortedImg, nil)
			default:
				fmt.Printf("Unsupported image format %v\n", format)
				os.Exit(-1)
			}
		}
	}
}
Exemplo n.º 15
0
func (ppu *RP2C02) SavePatternTables() (left, right *image.RGBA) {
	left, right = ppu.GetPatternTables()

	fo, _ := os.Create(fmt.Sprintf("left.jpg"))
	w := bufio.NewWriter(fo)
	jpeg.Encode(w, left, &jpeg.Options{Quality: 100})

	fo, _ = os.Create(fmt.Sprintf("right.jpg"))
	w = bufio.NewWriter(fo)
	jpeg.Encode(w, right, &jpeg.Options{Quality: 100})

	return
}
Exemplo n.º 16
0
func (ppu *RP2C02) dumpPatternTables() (left, right *image.RGBA) {
	left = image.NewRGBA(image.Rect(0, 0, 128, 128))
	right = image.NewRGBA(image.Rect(0, 0, 128, 128))

	colors := [4]color.RGBA{
		color.RGBA{0, 0, 0, 255},
		color.RGBA{203, 79, 15, 255},
		color.RGBA{255, 155, 59, 255},
		color.RGBA{255, 231, 163, 255},
	}

	x_base := 0
	y_base := 0

	ptimg := left

	for address := uint16(0x0000); address <= 0x1fff; address += 0x0010 {
		if address < 0x1000 {
			ptimg = left
		} else {
			ptimg = right
		}

		for row := uint16(0); row <= 7; row++ {
			low := ppu.Memory.Fetch(address + row)
			high := ppu.Memory.Fetch(address + row + 8)

			for i := int16(7); i >= 0; i-- {
				b := ((low >> uint16(i)) & 0x0001) | (((high >> uint16(i)) & 0x0001) << 1)
				ptimg.Set(x_base+(8-int(i+1)), y_base+int(row), colors[b])
			}
		}

		x_base += 8

		if x_base == 128 {
			x_base = 0
			y_base = (y_base + 8) % 128
		}
	}

	fo, _ := os.Create(fmt.Sprintf("left.jpg"))
	w := bufio.NewWriter(fo)
	jpeg.Encode(w, left, &jpeg.Options{Quality: 100})

	fo, _ = os.Create(fmt.Sprintf("right.jpg"))
	w = bufio.NewWriter(fo)
	jpeg.Encode(w, right, &jpeg.Options{Quality: 100})

	return
}
Exemplo n.º 17
0
// Resizing endpoint.
func resizing(w http.ResponseWriter, r *http.Request) {
	size := new(Size)

	// Get parameters
	imageUrl := r.FormValue("image")
	size.Width, _ = parseInteger(r.FormValue("width"))
	size.Height, _ = parseInteger(r.FormValue("height"))

	validator := Validator{config}

	if err := validator.CheckHostInWhiteList(imageUrl); err != nil {
		formatError(err, w)
		return
	}

	if err := validator.CheckRequestNewSize(size); err != nil {
		formatError(err, w)
		return
	}

	// Download the image
	imageBuffer, err := http.Get(imageUrl)

	if err != nil {
		formatError(err, w)
		return
	}

	finalImage, _, _ := image.Decode(imageBuffer.Body)
	r.Body.Close()

	imageResized := resize.Resize(size.Width, size.Height, finalImage, resize.Lanczos3)

	contentType := imageBuffer.Header.Get("Content-Type")
	switch contentType {
	case "image/png":
		png.Encode(w, imageResized)
		log.Printf("Successfully handled content type '%s'\n", contentType)
	case "image/jpeg":
		jpeg.Encode(w, imageResized, nil)
		log.Printf("Successfully handled content type '%s'\n", contentType)
	case "binary/octet-stream":
		jpeg.Encode(w, imageResized, nil)
		log.Printf("Successfully handled content type '%s'\n", contentType)
	default:
		log.Printf("Cannot handle content type '%s'\n", contentType)
	}
}
Exemplo n.º 18
0
/*
生成图片缩略图函数
*/
func (this *AdminController) Thumbnail(path, name string, size uint, style bool) error {
	//获取图片后缀和图片完整地址
	houzhui := name[strings.LastIndex(name, "."):]
	realpath := path + name
	// 打开图片
	file, err := os.Open(realpath)
	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(size, size, img, resize.Lanczos3)
	//如果是大头像
	if style {
		out, err := os.Create(path + "facebig" + houzhui)
		if err != nil {
			log.Fatal(err)
		}
		defer out.Close()
		// write new image to file
		err = jpeg.Encode(out, m, nil)
		if err != nil {
			return err
		}
		return nil
	} else {
		out, err := os.Create(path + "facesmall" + houzhui)
		if err != nil {
			log.Fatal(err)
		}
		defer out.Close()
		// write new image to file
		err = jpeg.Encode(out, m, nil)
		if err != nil {
			return err
		}
		return nil
	}

}
Exemplo n.º 19
0
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)
}
Exemplo n.º 20
0
// 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()
}
Exemplo n.º 21
0
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

}
Exemplo n.º 22
0
// imgHandler is the HTTP handler for displaying images and painting
// moustaches; it handles "/img".
func imgHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	key := datastore.NewKey(c, "Image", r.FormValue("id"), 0, nil)
	im := new(Image)
	if err := datastore.Get(c, key, im); err != nil {
		writeError(w, r, err)
		return
	}

	m, _, err := image.Decode(bytes.NewBuffer(im.Data))
	if err != nil {
		writeError(w, r, err)
		return
	}

	get := func(n string) int { // helper closure
		i, _ := strconv.Atoi(r.FormValue(n))
		return i
	}
	x, y, s, d := get("x"), get("y"), get("s"), get("d")

	if x > 0 { // only draw if coordinates provided
		m = moustache(m, x, y, s, d)
	}

	b := &bytes.Buffer{}
	if err := jpeg.Encode(w, m, nil); err != nil {
		writeError(w, r, err)
		return
	}
	w.Header().Set("Content-type", "image/jpeg")
	b.WriteTo(w)
}
Exemplo n.º 23
0
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)
}
Exemplo n.º 24
0
func main() {
	var file *os.File
	var outFile *os.File
	var img image.Image
	var err error

	if file, err = os.Open("pkg.png"); err != nil {
		println("Error", err)
		return
	}
	defer file.Close()

	if img, err = png.Decode(file); err != nil {
		println("Error", err)
		return
	}

	if outFile, err = os.Create("out_pkg.jpeg"); err != nil {
		println("Error", err)
		return
	}

	option := &jpeg.Options{Quality: 100}
	if err = jpeg.Encode(outFile, img, option); err != nil {
		println()
		return
	}
	defer outFile.Close()
}
Exemplo n.º 25
0
func generateThumbnailImage(img image.Image, thumbnailPath string, width int, height int) {
	thumbWidth := float64(utils.Cfg.FileSettings.ThumbnailWidth)
	thumbHeight := float64(utils.Cfg.FileSettings.ThumbnailHeight)
	imgWidth := float64(width)
	imgHeight := float64(height)

	var thumbnail image.Image
	if imgHeight < thumbHeight && imgWidth < thumbWidth {
		thumbnail = img
	} else if imgHeight/imgWidth < thumbHeight/thumbWidth {
		thumbnail = imaging.Resize(img, 0, utils.Cfg.FileSettings.ThumbnailHeight, imaging.Lanczos)
	} else {
		thumbnail = imaging.Resize(img, utils.Cfg.FileSettings.ThumbnailWidth, 0, imaging.Lanczos)
	}

	buf := new(bytes.Buffer)
	if err := jpeg.Encode(buf, thumbnail, &jpeg.Options{Quality: 90}); err != nil {
		l4g.Error(utils.T("api.file.handle_images_forget.encode_jpeg.error"), thumbnailPath, err)
		return
	}

	if err := WriteFile(buf.Bytes(), thumbnailPath); err != nil {
		l4g.Error(utils.T("api.file.handle_images_forget.upload_thumb.error"), thumbnailPath, err)
		return
	}
}
Exemplo n.º 26
0
// GenerateRandomAvatar generates a random avatar for user.
func (u *User) GenerateRandomAvatar() error {
	seed := u.Email
	if len(seed) == 0 {
		seed = u.Name
	}

	img, err := avatar.RandomImage([]byte(seed))
	if err != nil {
		return fmt.Errorf("RandomImage: %v", err)
	}
	if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
		return fmt.Errorf("MkdirAll: %v", err)
	}
	fw, err := os.Create(u.CustomAvatarPath())
	if err != nil {
		return fmt.Errorf("Create: %v", err)
	}
	defer fw.Close()

	if err = jpeg.Encode(fw, img, nil); err != nil {
		return fmt.Errorf("Encode: %v", err)
	}

	log.Info("New random avatar created: %d", u.Id)
	return nil
}
Exemplo n.º 27
0
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
}
Exemplo n.º 28
0
// 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)
}
Exemplo n.º 29
0
func (h mjpegHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "multipart/x-mixed-replace;boundary=--BOUNDARY")
	for {
		img := <-h
		_, err := fmt.Fprint(w, "--BOUNDARY\r\n"+
			"Content-Type: image/jpeg\r\n"+
			//"Content-Length:" + length + "\r\n" +
			"\r\n")
		if err != nil {
			nErrors++
			http.Error(w, err.Error(), 500)
			return
		}

		tEnc.Start()
		err = jpeg.Encode(w, img, &jpeg.Options{Quality: *flagQuality})
		tEnc.Stop()
		if err != nil {
			nErrors++
			http.Error(w, err.Error(), 500)
			return
		}
		nStreamed++
	}
}
Exemplo n.º 30
-1
func imgServingExample2(w http.ResponseWriter, r *http.Request) {

	c := appengine.NewContext(r)

	// prepare a rectangle
	var p1, p2 image.Point
	p1.X, p1.Y = 10, 10
	p2.X, p2.Y = 400, 255
	var rec image.Rectangle = image.Rectangle{Min: p1, Max: p2}

	// prepare a line color
	lineCol := color.RGBA{}
	lineCol.R, lineCol.G, lineCol.B = 255, 44, 22
	//lineCol.A = 0
	c.Infof("brush color %#v \n", lineCol)

	// create empty memory image - all pixels are 0 => black
	imgRGBA := image.NewRGBA(rec)

	for i := 20; i < 140; i++ {
		lineCol.A = uint8(i)
		imgRGBA.Set(i, i, lineCol)
		imgRGBA.Set(i+1, i, lineCol)
		imgRGBA.Set(i+2, i, lineCol)
		imgRGBA.Set(i+3, i, lineCol)
		imgRGBA.Set(i+3, i+1, lineCol)
	}
	w.Header().Set("Content-Type", "image/jpeg")
	jpeg.Encode(w, imgRGBA, &jpeg.Options{Quality: jpeg.DefaultQuality})

}