當前位置: 首頁>>代碼示例>>Golang>>正文


Golang jpeg.Encode函數代碼示例

本文整理匯總了Golang中image/jpeg.Encode函數的典型用法代碼示例。如果您正苦於以下問題:Golang Encode函數的具體用法?Golang Encode怎麽用?Golang Encode使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Encode函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: waterMark

//水印
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()
}
開發者ID:elvizlai,項目名稱:MGBlog,代碼行數:31,代碼來源:file.go

示例2: writeImage

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
}
開發者ID:huayuxian,項目名稱:imongo,代碼行數:25,代碼來源:handler.go

示例3: MakeThumb

// 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
}
開發者ID:htruong,項目名稱:oryza,代碼行數:34,代碼來源:site.go

示例4: Encode

// 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
}
開發者ID:maleck13,項目名稱:locals-api,代碼行數:34,代碼來源:helpers.go

示例5: main

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()
}
開發者ID:brejoc,項目名稱:gosizr,代碼行數:26,代碼來源:gosizr.go

示例6: makeTestImages

// 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

}
開發者ID:rfistman,項目名稱:camlistore,代碼行數:32,代碼來源:fastjpeg_test.go

示例7: resizeThumbnail

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
}
開發者ID:athom,項目名稱:tenpu,代碼行數:27,代碼來源:handlers.go

示例8: Save

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
}
開發者ID:janicduplessis,項目名稱:projectgo,代碼行數:34,代碼來源:imageutilshandler.go

示例9: HandleImage

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
	})
}
開發者ID:renzuinc,項目名稱:goproxy,代碼行數:56,代碼來源:image.go

示例10: resizeThumbnail

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
}
開發者ID:jmptrader,項目名稱:tenpu,代碼行數:55,代碼來源:handlers.go

示例11: downloadImage

//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
}
開發者ID:Bootz,項目名稱:nzbcrawler,代碼行數:56,代碼來源:t_parser.go

示例12: Encode

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")
	}
}
開發者ID:jonsen,項目名稱:simple-image-manipulation,代碼行數:12,代碼來源:main.go

示例13: handler

// 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)
}
開發者ID:2young2simple,項目名稱:go-thanksgiving,代碼行數:54,代碼來源:app.go

示例14: main

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)
			}
		}
	}
}
開發者ID:awans,項目名稱:pixelsort,代碼行數:52,代碼來源:pixelsort.go

示例15: SavePatternTables

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
}
開發者ID:yueyong,項目名稱:nintengo,代碼行數:13,代碼來源:ppu.go


注:本文中的image/jpeg.Encode函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。