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


Golang png.Encode函數代碼示例

本文整理匯總了Golang中image/png.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: main

func main() {
	var outFile *os.File
	var err error

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

	defer outFile.Close()

	rect := image.Rect(0, 0, 100, 100)
	rgba := image.NewRGBA64(rect)

	// #golangとか書きたいけど、とりあえず#だけ
	for i := 0; i < 10; i++ {
		rgba.Set(60, (10 + i), image.Black.At(0, 0))
		rgba.Set(65, (10 + i), image.Black.At(0, 0))
		rgba.Set((58 + i), 13, image.Black.At(0, 0))
		rgba.Set((58 + i), 16, image.Black.At(0, 0))
	}

	outImage := rgba.SubImage(rect)

	if err = png.Encode(outFile, outImage); err != nil {
		println("Error", err)
		return
	}

}
開發者ID:qt-luigi,項目名稱:golangcafe,代碼行數:30,代碼來源:createpng.go

示例3: httpMakeImage

func httpMakeImage() {
	s := rand.NewSource(time.Now().UnixNano())
	r := rand.New(s)

	pixelcount := f_httpImageSize / 4
	side := int(math.Sqrt(float64(pixelcount)))
	log.Debug("Image served will be %v by %v", side, side)

	m := image.NewRGBA(image.Rect(0, 0, side, side))
	for i := 0; i < len(m.Pix); i++ {
		m.Pix[i] = uint8(r.Int())
	}

	buf := new(bytes.Buffer)

	if *f_httpGzip {
		w := gzip.NewWriter(buf)
		png.Encode(w, m)
		w.Close()
	} else {
		png.Encode(buf, m)
	}

	httpImage = buf.Bytes()
}
開發者ID:cdshann,項目名稱:minimega,代碼行數:25,代碼來源:http.go

示例4: Save

// Save saves the texture as a PNG image.
func (a *TextureAtlas) Save(file string) (err error) {
	fd, err := os.Create(file)
	if err != nil {
		return
	}

	defer fd.Close()

	rect := image.Rect(0, 0, a.width, a.height)

	switch a.depth {
	case 1:
		img := image.NewAlpha(rect)
		copy(img.Pix, a.data)
		err = png.Encode(fd, img)

	case 3:
		img := image.NewRGBA(rect)
		copy(img.Pix, a.data)
		err = png.Encode(fd, img)

	case 4:
		img := image.NewRGBA(rect)
		copy(img.Pix, a.data)
		err = png.Encode(fd, img)
	}

	return
}
開發者ID:jasonrpowers,項目名稱:glh,代碼行數:30,代碼來源:atlas.go

示例5: OnElite

func (ec *myEliteConsumer) OnElite(g *ga.IGenome) {
	bits := (*g).GetBits()
	newImage := createImageFromBitset(bits)

	// Output elite
	outputImageFile, _ := os.Create("elite.png")
	png.Encode(outputImageFile, newImage)
	outputImageFile.Close()

	// Output elite with input image blended over the top
	outputImageFileAlphaBlended, _ := os.Create("elite_with_original.png")
	draw.DrawMask(newImage, newImage.Bounds(),
		inputImage, image.ZP,
		&image.Uniform{color.RGBA{0, 0, 0, 255 / 4}}, image.ZP,
		draw.Over)
	png.Encode(outputImageFileAlphaBlended, newImage)
	outputImageFileAlphaBlended.Close()

	ec.currentIter++
	fitness := (*g).GetFitness()
	fmt.Println(ec.currentIter, "\t", fitness, "\t", fitness-ec.previousFitness)

	ec.previousFitness = fitness

	time.Sleep(10 * time.Millisecond)
}
開發者ID:tomcraven,項目名稱:goga,代碼行數:26,代碼來源:elite_consumer.go

示例6: main

func main() {
	w := 16
	h := 16
	img := image.NewRGBA(image.Rect(0, 0, w, h))
	col := color.RGBA{255, 0, 0, 255}
	for x := 0; x < w; x++ {
		if x > 8 {
			col = color.RGBA{0, 0, 255, 255}
		}
		for y := 0; y < h; y++ {
			img.Set(x, y, col)
		}
	}

	// 通過bytes創建writer
	// http://stackoverflow.com/questions/23454940/getting-bytes-buffer-does-not-implement-io-writer-error-message
	var b bytes.Buffer
	foo := bufio.NewWriter(&b)
	png.Encode(foo, img)
	foo.Flush()
	log.Println(b)
	data := b.Bytes()
	// 使用base64編碼後,將str複製到瀏覽器中可以直接顯示
	str := base64.StdEncoding.EncodeToString(data)
	str = "data:image/png;base64," + str
	log.Println(str)

	f, err := os.Create("test.png")
	if err != nil {
		panic(err)
	}
	defer f.Close()
	png.Encode(f, img)
}
開發者ID:gonewbee,項目名稱:myTest,代碼行數:34,代碼來源:testpng.go

示例7: TestGMProcess

func TestGMProcess(t *testing.T) {
	buffer := new(bytes.Buffer)
	png.Encode(buffer, image.NewRGBA(image.Rect(0, 0, 200, 200)))

	gm := NewGMProcessor()
	params, _ := ParseParams("r_100x100,c_50x50,g_c,q_50")
	img, err := gm.Process(params, "text.png", buffer)
	assert.NoError(t, err)
	assert.NotNil(t, img)
	assert.True(t, img.Len() > 0)

	buffer = new(bytes.Buffer)
	png.Encode(buffer, image.NewRGBA(image.Rect(0, 0, 200, 200)))
	params, _ = ParseParams("r_100x0,c_50x50,g_c,q_50")
	img, err = gm.Process(params, "text.png", buffer)
	assert.NoError(t, err)
	assert.NotNil(t, img)
	assert.True(t, img.Len() > 0)

	buffer = new(bytes.Buffer)
	png.Encode(buffer, image.NewRGBA(image.Rect(0, 0, 200, 200)))
	params, _ = ParseParams("r_0x100,c_50x50,g_c,q_50")
	img, err = gm.Process(params, "text.png", buffer)
	assert.NoError(t, err)
	assert.NotNil(t, img)
	assert.True(t, img.Len() > 0)
}
開發者ID:maxid,項目名稱:ivy,代碼行數:27,代碼來源:gm_test.go

示例8: to_img

func to_img(brot *[size][size]uint, max uint) {
	gray := image.NewGray16(image.Rect(0, 0, size, size))
	norm_gray := image.NewGray16(image.Rect(0, 0, size, size))
	for x := 0; x < size; x++ {
		for y := 0; y < size; y++ {
			pix := brot[x][y]
			norm := float64(brot[x][y]*4) / float64(max) * 65534
			if norm > 65534 {
				norm = 65534
			}
			if pix > 65534 {
				pix = 65534
			}
			gray.SetGray16(
				x, y,
				color.Gray16{uint16(pix)})
			norm_gray.SetGray16(
				x, y,
				color.Gray16{uint16(norm)})
		}
	}
	w, _ := os.OpenFile("./brot.png", os.O_CREATE|os.O_WRONLY, 0666)
	png.Encode(w, gray)
	n, _ := os.OpenFile("./brot-norm.png", os.O_CREATE|os.O_WRONLY, 0666)
	png.Encode(n, norm_gray)
}
開發者ID:rciorba,項目名稱:frac,代碼行數:26,代碼來源:buddah.go

示例9: main

func main() {
	// quality := flag.Float64("quality", 0.7, "Quality of compression.")
	benchmark := flag.Bool("benchmark", false, "Benchmark it.")
	iterations := flag.Int("iterations", 100, "Iterations for benchmark")
	flag.Parse()

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	filename := flag.Arg(0)

	if *benchmark {
		start := time.Now()
		b := gutils.Screenshot().Bounds()
		buf := make([]byte, b.Dx()*b.Dy()*4)
		w := bytes.NewBuffer(buf)
		for i := 0; i < *iterations; i++ {
			m := gutils.Screenshot()
			if filename != "" {
				// f, err := os.Create(filename)
				// if err != nil {
				// 	fmt.Println("Benchmark failed:", err)
				// 	return
				// }
				start := time.Now()
				// jpeg.Encode(w, m, nil)
				png.Encode(w, m)
				fmt.Println(time.Since(start))
				// f.Close()
			}
		}
		delta := time.Now().Sub(start)
		usedDisk := filename != ""
		fmt.Printf(
			"Result: iterations=%d, time=%s, fps=%d, disk=%t.\n", *iterations,
			delta, *iterations*1e9/int(delta), usedDisk,
		)
	} else {
		if filename == "" {
			fmt.Println("Filename required.")
			return
		}

		m := gutils.Screenshot()
		f, err := os.Create(filename)
		if err != nil {
			fmt.Println("Benchmark failed:", err)
			return
		}
		png.Encode(f, m)
		f.Close()
	}
}
開發者ID:gauravagarwalr,項目名稱:gutils,代碼行數:59,代碼來源:new.go

示例10: 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

示例11: Julia

func Julia(tType int, config Config) func(http.ResponseWriter, *http.Request, httprouter.Params) {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		width, err := strconv.Atoi(ps.ByName("width"))
		if err != nil {
			width = 800
		}
		height, err := strconv.Atoi(ps.ByName("height"))
		if err != nil {
			height = 600
		}

		real, err := strconv.ParseFloat(ps.ByName("r"), 32)
		if err != nil {
			real = 1
		}

		imaginary, err := strconv.ParseFloat(ps.ByName("i"), 32)
		if err != nil {
			imaginary = 0.1
		}

		if height < 200 {
			height = 200
		} else if height > 1080 {
			height = 1080
		}
		if width < 320 {
			width = 320
		} else if width > 1920 {
			width = 1920
		}
		fileName := fmt.Sprintf("%s/juliasin-%d-%d-(%.16f)-(%.16f).png", config.CachePath, width, height, real, imaginary)

		fileData, err := ioutil.ReadFile(fileName)
		if err != nil || config.NoCache {
			fractalImage := fractalgen.Julia(tType, width, height, complex(real, imaginary))
			if !config.NoCache {
				f, err := os.Create(fileName)
				if err == nil {
					png.Encode(f, fractalImage)
					f.Close()
				}
			}

			w.Header().Set("Content-Type", "image/png")
			png.Encode(w, fractalImage)
		} else {
			w.Header().Set("Content-Type", "image/png")
			w.Write(fileData)
		}

	}

}
開發者ID:wturyn,項目名稱:go-web-fractal,代碼行數:54,代碼來源:handlers.go

示例12: SaveImage

func SaveImage(width, height int, frame *Frame, fn string) {
	out, err := os.Create("./output/" + makeTimestamp() + ".png")
	FailGracefully(err)
	out2, err := os.Create("./output/" + fn + ".png")
	FailGracefully(err)

	fmt.Println("Saving As: ", makeTimestamp())

	go FailGracefully(png.Encode(out, frame))
	go FailGracefully(png.Encode(out2, frame))
}
開發者ID:kctess5,項目名稱:Golang-Sample-Interpolation-Engine,代碼行數:11,代碼來源:utils.go

示例13: makeComic

func (p *comicPlugin) makeComic(bot *bruxism.Bot, service bruxism.Service, message bruxism.Message, script *comicgen.Script) {
	p.Comics++
	comic := comicgen.NewComicGen("arial", service.Name() != bruxism.DiscordServiceName)
	image, err := comic.MakeComic(script)
	if err != nil {
		service.SendMessage(message.Channel(), fmt.Sprintf("Sorry %s, there was an error creating the comic. %s", message.UserName(), err))
	} else {
		go func() {
			if service.Name() == bruxism.DiscordServiceName {
				discord := service.(*bruxism.Discord)
				p, err := discord.UserChannelPermissions(message.UserID(), message.Channel())
				if err == nil && p&discordgo.PermissionAttachFiles != 0 {
					b := &bytes.Buffer{}
					err = png.Encode(b, image)
					if err != nil {
						service.SendMessage(message.Channel(), fmt.Sprintf("Sorry %s, there was a problem creating your comic.", message.UserName()))
						return
					}

					if err := service.SendFile(message.Channel(), "comic.png", b); err == nil {
						return
					}
				}
			}

			b := &bytes.Buffer{}
			err = png.Encode(b, image)
			if err != nil {
				service.SendMessage(message.Channel(), fmt.Sprintf("Sorry %s, there was a problem creating your comic.", message.UserName()))
				return
			}

			url, err := bot.UploadToImgur(b, "comic.png")
			if err != nil {
				service.SendMessage(message.Channel(), fmt.Sprintf("Sorry %s, there was a problem uploading the comic to imgur.", message.UserName()))
				log.Println("Error uploading comic: ", err)
				return
			}

			if service.Name() == bruxism.DiscordServiceName {
				service.SendMessage(message.Channel(), fmt.Sprintf("Here's your comic <@%s>: %s", message.UserID(), url))
			} else {
				service.SendMessage(message.Channel(), fmt.Sprintf("Here's your comic %s: %s", message.UserName(), url))
			}

			runtime.GC()
		}()
	}
}
開發者ID:iopred,項目名稱:bruxism,代碼行數:49,代碼來源:comicplugin.go

示例14: processLayer

func processLayer(t *testing.T, f string, l *Layer) error {
	if len(l.Layer) > 0 {
		for i, ll := range l.Layer {
			if err := processLayer(t, fmt.Sprintf("%s_%d", f, i), &ll); err != nil {
				return err
			}
		}
	}
	if !l.HasImage() {
		return nil
	}

	// write layer image per channel
	for id, ch := range l.Channel {
		if err := func() error {
			o, err := os.Create(fmt.Sprintf("output/%s_Ch%d.png", f, id))
			if err != nil {
				return err
			}
			defer o.Close()
			return png.Encode(o, ch.Picker)
		}(); err != nil {
			return err
		}
	}

	for id, ch := range l.Channel {
		verifyChannel(
			t,
			fmt.Sprintf("%s Ch:%d", f, id),
			fmt.Sprintf("png/%s_Ch%d.png", f, id),
			ch.Picker,
		)
	}

	// write layer image
	o, err := os.Create(fmt.Sprintf("output/%s.png", f))
	if err != nil {
		return err
	}
	defer o.Close()
	err = png.Encode(o, l.Picker)
	if err != nil {
		return err
	}

	verifyImage(t, f, fmt.Sprintf("png/%s.png", f), l.Picker)
	return nil
}
開發者ID:oov,項目名稱:psd,代碼行數:49,代碼來源:psd_test.go

示例15: UploadAvatar

// 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()
}
開發者ID:jessezwd,項目名稱:gogs,代碼行數:34,代碼來源:user.go


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