Golang Draw示例

说明

golang draw示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: image/draw

示例#1
文件: file.go 项目: elvizlai/MGBlog

//水印
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()
}

示例#2
文件: LightPane.go 项目: lindsaymarkward/sphere-go-led-controller

func (p *LightPane) Render() (*image.RGBA, error) {
	canvas := image.NewRGBA(image.Rect(0, 0, width, height))

	if p.colorMode {
		c := colorful.Hsv(p.airWheelState*360, 1, 1)
		draw.Draw(canvas, canvas.Bounds(), &image.Uniform{color.RGBA{uint8(c.R * 255), uint8(c.G * 255), uint8(c.B * 255), 255}}, image.ZP, draw.Src)
	} else {

		brightness := uint8(p.airWheelState * 255)
		if brightness < brightnessMinimum {
			brightness = brightnessMinimum
		}

		draw.Draw(canvas, canvas.Bounds(), &image.Uniform{color.RGBA{brightness, brightness, brightness, 255}}, image.ZP, draw.Src)
	}

	var frame *image.RGBA
	if p.onOffState {
		frame = p.onImage.GetNextFrame()
	} else {
		frame = p.offImage.GetNextFrame()
	}

	draw.Draw(canvas, canvas.Bounds(), frame, image.ZP, draw.Over)

	return canvas, nil
}

示例#3
文件: logos.go 项目: pyisoeyz/chaparty

func addLogo(profilePtr *image.Image, logo string, context appengine.Context) []byte {
	profileImage := *profilePtr
	destImage := image.NewRGBA(profileImage.Bounds())
	draw.Draw(destImage, destImage.Bounds(), profileImage, image.ZP, draw.Src)

	if logoImages, ok := THELOGOIMAGES[logo]; ok {
		randi := rand.Intn(len(logoImages))
		logoImage := logoImages[randi]

		offset := image.Pt(5, 5)
		if strings.HasPrefix(logo, "NLD-") {
			offset = image.Pt(0, 0)
		}

		start := profileImage.Bounds().Size()
		start = start.Sub(offset)
		start = start.Sub(logoImage.Bounds().Size())

		bounds := image.Rectangle{start, start.Add(logoImage.Bounds().Size())}
		draw.Draw(destImage, bounds, logoImage, image.ZP, draw.Over)

	} else {
		context.Errorf("Cannot load logoimage for %s", logo)
	}

	buffer := new(bytes.Buffer)
	err := png.Encode(buffer, destImage)
	check(err, context)

	return buffer.Bytes()
}

示例#4
文件: jwed.go 项目: MasterScrat/bgfileformats

func (jw *JsonWed) ImportOverlays(wed *Wed) error {
	jw.Overlays = make([]jsonWedOverlay, 0)
	jw.TileIndices = make([]int, len(wed.TileIndices))
	for idx, overlay := range wed.Overlays {
		if overlay.Name.String() != "" {
			ov := jsonWedOverlay{}
			ov.Width = int(overlay.Width)
			ov.Height = int(overlay.Height)
			ov.Name = overlay.Name.String()
			ov.Flags = int(overlay.LayerFlags)

			ov.Tilemap = make([]jsonWedTilemap, len(wed.Tilemaps[idx]))
			for tmIdx, tilemap := range wed.Tilemaps[idx] {
				ov.Tilemap[tmIdx].Id = int(tilemap.TileIndexLookupIndex)
				ov.Tilemap[tmIdx].Count = int(tilemap.TileIndexLookupCount)
				ov.Tilemap[tmIdx].Alt = int(tilemap.AlternateTileIndex)
				ov.Tilemap[tmIdx].Flags = int(tilemap.Flags)
				ov.Tilemap[tmIdx].AnimSpeed = int(tilemap.AnimSpeed)
				ov.Tilemap[tmIdx].WFlags = int(tilemap.WFlags)
			}

			tisFile, err := os.Open(overlay.Name.String() + ".tis")
			if err != nil {
				return fmt.Errorf("unable to open overlay: %s %v", overlay.Name.String(), err)
			}
			defer tisFile.Close()

			cwd, err := os.Getwd()
			if err != nil {
				return fmt.Errorf("unable to get working directory: %v", err)
			}
			tis, err := OpenTis(tisFile, overlay.Name.String(), cwd)
			if err != nil {
				return fmt.Errorf("unable to open tis: %v", err)
			}
			ov.Tis = tis
			img := image.NewRGBA(image.Rect(0, 0, 64*ov.Width, 64*ov.Height))
			closedimg := image.NewRGBA(image.Rect(0, 0, 64*ov.Width, 64*ov.Height))
			for y := 0; y < int(ov.Height); y++ {
				for x := 0; x < int(ov.Width); x++ {
					tileNum := y*int(ov.Width) + x
					tileImg := tis.SubImage(tileNum)
					draw.Draw(img, image.Rect(x*64, y*64, x*64+64, y*64+64), tileImg, image.Pt(0, 0), draw.Src)
					if ov.Tilemap[tileNum].Alt != -1 {
						tileImg = tis.SubImage(ov.Tilemap[tileNum].Alt)
						draw.Draw(closedimg, image.Rect(x*64, y*64, x*64+64, y*64+64), tileImg, image.Pt(0, 0), draw.Src)
					}
				}
			}
			ov.BackgroundImg = img
			ov.ClosedImage = closedimg

			jw.Overlays = append(jw.Overlays, ov)
		}
	}
	for idx, ti := range wed.TileIndices {
		jw.TileIndices[idx] = int(ti)
	}
	return nil
}

示例#5
文件: gui.go 项目: mewmew/playground

// Render renders the grid each time a value is sent on the render channel.
func Render(win wde.Window, g *grid.Grid, render chan bool) {
	screen := win.Screen()
	bounds := screen.Bounds()
	grey := image.NewUniform(color.RGBA{R: 0xF9, G: 0xF9, B: 0xF9}) /// ### todo ### A: 0xFF?
	for {
		<-render

		// Draw grid background.
		draw.Draw(screen, bounds, grey, image.ZP, draw.Src)
		draw.Draw(screen, bounds, imgGrid, image.ZP, draw.Over)

		// Draw grid markers.
		var img image.Image
		for col := 0; col < g.Width(); col++ {
			for row := 0; row < g.Height(); row++ {
				switch g[col][row] {
				case grid.MarkO:
					img = imgO
				case grid.MarkX:
					img = imgX
				default:
					continue
				}
				pt := getCellPt(col, row, g[col][row])
				rect := image.Rect(0, 0, img.Bounds().Dx(), img.Bounds().Dy())
				draw.Draw(screen, rect.Add(pt), img, image.ZP, draw.Over)
			}
		}

		// Flush screen updates.
		win.FlushImage(bounds)
	}
}

示例#6
文件: mask.go 项目: Chubik/testgolang

func main() {
	pngImgFile, err := os.Open("./2.png")

	if err != nil {
		fmt.Println("2.png file not found!")
		os.Exit(1)
	}

	defer pngImgFile.Close()

	imgSrc, err := png.Decode(pngImgFile)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	newImg := image.NewRGBA(imgSrc.Bounds())
	draw.Draw(newImg, newImg.Bounds(), &image.Uniform{color.White}, image.Point{}, draw.Src)

	draw.Draw(newImg, newImg.Bounds(), imgSrc, imgSrc.Bounds().Min, draw.Over)

	jpgImgFile, err := os.Create("./draw.jpg")

	if err != nil {
		fmt.Println("Cannot create draw.jpg !")
		fmt.Println(err)
		os.Exit(1)
	}

	defer jpgImgFile.Close()
}

示例#7
文件: crop.go 项目: tylercoville/ResizeImgServer

func Crop(img image.Image, width int, height int, padding int) (fimg draw.Image, err error) {
	// For now assume top left is bg color
	// future maybe avg outer rows of pixels
	bgcolor := img.At(img.Bounds().Min.X, img.Bounds().Min.Y)
	logoh, logow := height-2*padding, width-2*padding
	logorat := float32(logow) / float32(logoh)

	interior := findLogo(img, bgcolor)
	interior.Max = interior.Max.Add(image.Pt(1, 1))

	center := func(rect image.Rectangle) image.Point {
		return image.Point{(rect.Max.X - rect.Min.X) / 2, (rect.Max.Y - rect.Min.Y) / 2}
	}
	fimg = image.NewRGBA(image.Rect(0, 0, width, height))

	rc := center(fimg.Bounds())
	origrat := float32(interior.Dx()) / float32(interior.Dy())

	if logorat > origrat {
		logow = int(origrat * float32(logoh))
	} else {
		logoh = int(float32(logow) / origrat)
	}
	logoimg := Resize(img, interior, logow, logoh)

	logorect := image.Rect(0, 0, logoimg.Bounds().Dx(), logoimg.Bounds().Dy())
	logorect = logorect.Add(rc.Sub(image.Pt(logorect.Dx()/2, logorect.Dy()/2)))

	draw.Draw(fimg, fimg.Bounds(), &image.Uniform{bgcolor}, image.ZP, draw.Src)
	draw.Draw(fimg, logorect, logoimg, image.ZP, draw.Src)
	return
}

示例#8
文件: qrcode.go 项目: raistlinzx/go-qrcode

func DrawLogo(qrPng []byte, logo string, logoBgColor color.Color) []byte {

	if logo != "" {
		// println(logo)
		resp, err := http.Get(logo)

		if err != nil {
			fmt.Printf("Logo Error=%s\n", err.Error())
			// println(resp)
		} else {

			logoImg, _, _ := image.Decode(resp.Body)
			qrImg, _, _ := image.Decode(bytes.NewReader(qrPng))
			pb := qrImg.Bounds()
			logoImg = resize.Resize(uint(pb.Dx()/4), uint(pb.Dy()/4), logoImg, resize.Lanczos3)
			logoBgImg := image.NewRGBA(image.Rect(0, 0, logoImg.Bounds().Dx()+2, logoImg.Bounds().Dy()+2))
			draw.Draw(logoBgImg, logoBgImg.Bounds(), &image.Uniform{color.White}, image.Point{}, draw.Src)
			draw.Draw(logoBgImg, logoImg.Bounds(), logoImg, image.Point{-1, -1}, draw.Over)

			offsetX := (pb.Dx() - logoBgImg.Bounds().Dx()) / 2
			newImg := image.NewRGBA(pb)
			draw.Draw(newImg, pb, qrImg, image.Point{}, draw.Src)
			draw.Draw(newImg, newImg.Bounds(), logoBgImg, image.Point{-offsetX, -offsetX}, draw.Over)
			// println(logoImg)
			buf := new(bytes.Buffer)
			err = png.Encode(buf, newImg)
			// send_s3 := buf.Bytes()
			return buf.Bytes()

		}
	}
	return qrPng
}

示例#9
文件: colorgens.go 项目: ReshNesh/go-colorful

func main() {
	blocks := 10
	blockw := 40
	space := 5

	rand.Seed(time.Now().UTC().UnixNano())
	img := image.NewRGBA(image.Rect(0, 0, blocks*blockw+space*(blocks-1), 4*(blockw+space)))

	for i := 0; i < blocks; i++ {
		warm := colorful.WarmColor()
		fwarm := colorful.FastWarmColor()
		happy := colorful.HappyColor()
		fhappy := colorful.FastHappyColor()
		draw.Draw(img, image.Rect(i*(blockw+space), 0, i*(blockw+space)+blockw, blockw), &image.Uniform{warm}, image.ZP, draw.Src)
		draw.Draw(img, image.Rect(i*(blockw+space), blockw+space, i*(blockw+space)+blockw, 2*blockw+space), &image.Uniform{fwarm}, image.ZP, draw.Src)
		draw.Draw(img, image.Rect(i*(blockw+space), 2*blockw+3*space, i*(blockw+space)+blockw, 3*blockw+3*space), &image.Uniform{happy}, image.ZP, draw.Src)
		draw.Draw(img, image.Rect(i*(blockw+space), 3*blockw+4*space, i*(blockw+space)+blockw, 4*blockw+4*space), &image.Uniform{fhappy}, image.ZP, draw.Src)
	}

	toimg, err := os.Create("colorgens.png")
	if err != nil {
		fmt.Printf("Error: %v", err)
		return
	}
	defer toimg.Close()

	png.Encode(toimg, img)
}

示例#10
文件: ukrcode.go 项目: denys-potapov/ukrcode

func hor(code barcode.Barcode, scale int) image.Image {
	b := NewBitmap(code)
	img := image.NewRGBA(image.Rect(0, 0, b.height*scale, b.width*scale))
	draw.Draw(img, img.Bounds(), &image.Uniform{white}, image.ZP, draw.Src)

	patterns := [][][]int{
		{{any, set, any},
			{set, skp, set},
			{any, set, any}}}

	for _, pattern := range patterns {
		for y := 0; y < b.height; y++ {
			for x := 0; x < b.width; x++ {
				if Match(b, pattern, x, y) {
					Draw(img, b, pattern, x, y, scale)
				}
			}
		}
	}

	for y := 0; y < b.height; y++ {
		for x := 0; x < b.width; x++ {
			if b.Get(x, y) {
				pixel := image.Rect(x*scale, y*scale, (x+1)*scale, (y+1)*scale)
				draw.Draw(img, pixel, &image.Uniform{black}, image.ZP, draw.Src)
			}
		}
	}

	return img
}

示例#11
文件: window.go 项目: sebastianskejoe/Gough

func (w *Window) DrawFrame(frame int) {
	var f Frame
	var err os.Error

	if frame >= w.FrameCount {
		return
	}

	f = w.Frames[frame]

	if f.img == nil {
		f.img, err = getImage(f.Path)
		if err != nil {
			return
		}
	}
	draw.Draw(w.Screen, f.img.Bounds(), f.img, image.Point{0, 0}, draw.Over)

	if w.State == WORKING {
		draw.Draw(w.Screen, image.Rectangle{image.Point{0, 0}, image.Point{20, 20}},
			image.NewUniform(color.RGBA{0, 255, 0, 255}), image.Point{0, 0}, draw.Src)
	}

	DrawCircle(w.Screen, f.Centre.Centre, f.Centre.Radius, color.RGBA{0, 255, 255, 255})
	w.Window.FlushImage()
}

示例#12
文件: process.go 项目: spideynn/imgd

// Sets skin.Processed to an isometric render of the head from a top-left angle (showing 3 sides).
func (skin *mcSkin) GetCube(width int) error {
	// Crop out the top of the head
	topFlat := imaging.Crop(skin.Image, image.Rect(8, 0, 16, 8))
	// Resize appropriately, so that it fills the `width` when rotated 45 def.
	topFlat = imaging.Resize(topFlat, int(float64(width)*math.Sqrt(2)/3+1), 0, imaging.NearestNeighbor)
	// Create the Gift filter
	filter := gift.New(
		gift.Rotate(45, color.Transparent, gift.LinearInterpolation),
	)
	bounds := filter.Bounds(topFlat.Bounds())
	top := image.NewNRGBA(bounds)
	// Draw it on the filter, then smush it!
	filter.Draw(top, topFlat)
	top = imaging.Resize(top, width+2, width/3, imaging.NearestNeighbor)
	// Skew the front and sides at 15 degree angles to match up with the
	// head that has been smushed
	front := skin.cropHead(skin.Image).(*image.NRGBA)
	side := imaging.Crop(skin.Image, image.Rect(0, 8, 8, 16))
	front = imaging.Resize(front, width/2, int(float64(width)/1.75), imaging.NearestNeighbor)
	side = imaging.Resize(side, width/2, int(float64(width)/1.75), imaging.NearestNeighbor)
	front = skewVertical(front, math.Pi/12)
	side = skewVertical(imaging.FlipH(side), math.Pi/-12)

	// Create a new image to assemble upon
	skin.Processed = image.NewNRGBA(image.Rect(0, 0, width, width))
	// Draw each side
	draw.Draw(skin.Processed.(draw.Image), image.Rect(0, width/6, width/2, width), side, image.Pt(0, 0), draw.Src)
	draw.Draw(skin.Processed.(draw.Image), image.Rect(width/2, width/6, width, width), front, image.Pt(0, 0), draw.Src)
	// Draw the top we created
	draw.Draw(skin.Processed.(draw.Image), image.Rect(-1, 0, width+1, width/3), top, image.Pt(0, 0), draw.Over)

	return nil
}

示例#13
文件: createDigitalImage.go 项目: jabrena/skymapper

func createDigitalImage(imagePath string) {

	//Create an image object with some dimensions
	img := image.NewRGBA(image.Rect(0, 0, imageWidth, imageHeight))

	//Define colors used in the digital examples
	white, _ := colorful.Hex("#ffffff")
	red, _ := colorful.Hex("#ff0000")

	//Add a white background.
	draw.Draw(img, image.Rect(0, 0, imageWidth, imageHeight), &image.Uniform{white}, image.ZP, draw.Src)

	//Add some red blobs.
	draw.Draw(img, image.Rect(50, 50, 55, 55), &image.Uniform{red}, image.ZP, draw.Src)
	//draw.Draw(img, image.Rect(550, 50, 600, 100), &image.Uniform{red}, image.ZP, draw.Src)
	//draw.Draw(img, image.Rect(50, 300, 100, 350), &image.Uniform{red}, image.ZP, draw.Src)
	//draw.Draw(img, image.Rect(300, 200, 400, 300), &image.Uniform{red}, image.ZP, draw.Src)

	toimg, err := os.Create("digitalImage.png")
	if err != nil {
		fmt.Printf("Error: %v", err)
		return
	}
	defer toimg.Close()

	png.Encode(toimg, img)

}

示例#14
文件: text.go 项目: farhaven/universe

func (c *Context) RenderMultiline(txt []string, size float64, bg, fg color.Color) (*image.RGBA, error) {
	w, h := 0, 0
	imgs := []*image.RGBA{}

	for _, l := range txt {
		i, err := c.Render(l, size, fg)
		if err != nil {
			return nil, err
		}
		if i.Bounds().Dx() > w {
			w = i.Bounds().Dx()
		}
		h += i.Bounds().Dy()
		imgs = append(imgs, i)
	}

	dst := image.NewRGBA(image.Rect(0, 0, w, h))
	draw.Draw(dst, dst.Bounds(), image.NewUniform(bg), image.ZP, draw.Src)
	y := 0
	for _, src := range imgs {
		sr := src.Bounds()
		dp := image.Point{0, y}
		r := image.Rectangle{dp, dp.Add(sr.Size())}
		draw.Draw(dst, r, src, sr.Min, draw.Src)
		y += sr.Dy()
	}

	return dst, nil
}

示例#15
文件: png.go 项目: jorik041/buckler

func makePngShield(w io.Writer, d Data) {
	// render text to determine how wide the image has to be
	// we leave 6 pixels at the start and end, and 3 for each in the middle
	v, vw := renderString(d.Vendor, c)
	s, sw := renderString(d.Status, c)
	imageWidth := op + vw + ip*2 + sw + op

	img := image.NewRGBA(image.Rect(0, 0, imageWidth, h))
	draw.Draw(img, img.Bounds(), &image.Uniform{C: d.Color}, image.ZP, draw.Src)

	rect := image.Rect(0, 0, op+vw+ip, h)
	draw.Draw(img, rect, &image.Uniform{C: Grey}, image.ZP, draw.Src)

	dst := image.NewRGBA(image.Rect(0, 0, imageWidth, h))

	mask := image.NewRGBA(image.Rect(0, 0, imageWidth, h))
	buildMask(mask, imageWidth, edge, draw.Src)
	draw.DrawMask(dst, dst.Bounds(), img, image.ZP, mask, image.ZP, draw.Over)

	buildMask(dst, imageWidth, gradient, draw.Over)

	draw.Draw(dst, dst.Bounds(), v, image.Point{-op, 0}, draw.Over)

	draw.Draw(dst, dst.Bounds(), s, image.Point{-(op + vw + ip*2), 0}, draw.Over)

	png.Encode(w, dst)
}

示例#16
文件: send_mail.go 项目: jixiuf/mailaddrpasergo

func imageModify(filename string) (outFileName string) {
	// 对图片文件进行微处理,稍作修改以尽量避免被认为是垃圾邮件,每次发的图片md5都不同,
	outFileName = "tmp-" + filename
	f1, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer f1.Close()

	out, err := os.Create(outFileName)
	if err != nil {
		panic(err)
	}
	defer out.Close()

	m1, err := jpeg.Decode(f1)
	if err != nil {
		panic(err)
	}
	bounds := m1.Bounds()
	m := image.NewRGBA(bounds)
	draw.Draw(m, bounds, m1, image.ZP, draw.Src)

	bounds = image.Rect(0, 0, 5, 10)
	randomColor := color.RGBA{uint8(rand.Intn(255)), uint8(rand.Intn(255)), uint8(rand.Intn(255)), 255}
	draw.Draw(m, bounds, &image.Uniform{randomColor}, image.ZP, draw.Src)

	// draw.Draw(m, image.Rect(100, 200, 300, 600), m2, image.Pt(250, 60), draw.Src)
	err = jpeg.Encode(out, m, &jpeg.Options{90})
	if err != nil {
		panic(err)
	}
	return
}

示例#17
文件: pad.go 项目: cartermarino/streetsphere

// Pad reads a photosphere image and writes a padded 360 degree x 180 degree image to a given writer.
func Pad(w io.Writer, ir io.Reader) (pano *PanoOpts, err error) {
	d, err := ioutil.ReadAll(ir)
	if err != nil {
		return nil, err
	}

	r := bufio.NewReader(bytes.NewReader(d))
	for {
		s, err := NextSection(r, APP1)
		if err != nil {
			return nil, err
		}
		if s == nil {
			break
		}

		if IsXMP(s) {
			meta := new(XMPMeta)
			err := xml.Unmarshal(ExtractXMP(s), meta)
			if err != nil {
				// Not XMP?
				continue
			}
			if meta.PanoOpts.NS != "http://ns.google.com/photos/1.0/panorama/" {
				// Different XMP
				continue
			}
			pano = meta.PanoOpts
			break
		}
	}

	if pano == nil {
		return nil, errors.New("image provided had no photo sphere metadata")
	}

	src, err := jpeg.Decode(bytes.NewReader(d))
	if err != nil {
		return nil, err
	}
	srcB := src.Bounds()

	// Sometimes the height in the metadata doesn't match the actual height.
	// If that's the case, scale all of the other parameters.
	if srcB.Dy() != pano.Height {
		scale := float64(srcB.Dy()) / float64(pano.Height)
		pano.TotalHeight = int(float64(pano.TotalHeight) * scale)
		pano.TotalWidth = int(float64(pano.TotalWidth) * scale)
		pano.Top = int(float64(pano.Top) * scale)
		pano.Left = int(float64(pano.Left) * scale)
	}

	dst := image.NewRGBA(image.Rect(0, 0, pano.TotalWidth, pano.TotalHeight))
	draw.Draw(dst, dst.Bounds(), image.NewUniform(color.Black), image.ZP, draw.Src)
	compositeBounds := image.Rect(pano.Left, pano.Top, pano.Left+srcB.Dx(), pano.Top+srcB.Dy())
	draw.Draw(dst, compositeBounds, src, image.ZP, draw.Src)

	err = jpeg.Encode(w, dst, nil)
	return pano, err
}

示例#18
文件: handler.go 项目: aimin/ykthumb

// 水印
func watermark(file string, to string, w string) error {
	// 打开图片并解码
	origin, err := loadImg(file)

	// 打开水印图并解码
	watermark, err := loadImgSpecFormat(w, "png")
	if err != nil {
		return err
	}

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

	//创建新图层
	canvas := image.NewNRGBA(origin_size)
	// 贴原始图
	draw.Draw(canvas, origin_size, origin, image.ZP, draw.Src)
	// 贴水印图
	draw.Draw(canvas, watermark.Bounds().Add(image.Pt(30, 30)), watermark, image.ZP, draw.Over)

	//生成新图片
	create_image, err := os.Create(to)
	if err != nil {
		log.Fatal(err)
	}
	jpeg.Encode(create_image, canvas, &jpeg.Options{95})
	defer create_image.Close()
	return nil
}

示例#19
文件: main.go 项目: meatballhat/box-o-sand

func main() {
	flag.Parse()
	rand.Seed(time.Now().UTC().UnixNano())

	out, err := os.Create(*outfile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
		os.Exit(1)
	}

	imgRect := image.Rect(0, 0, 200, 200)
	img := image.NewGray(imgRect)
	draw.Draw(img, img.Bounds(), &image.Uniform{color.White}, image.ZP, draw.Src)

	for y := 0; y < 200; y += 10 {
		for x := 0; x < 200; x += 10 {
			fill := &image.Uniform{color.Black}
			if rand.Intn(10)%2 == 0 {
				fill = &image.Uniform{color.White}
			}

			draw.Draw(img, image.Rect(x, y, x+10, y+10), fill, image.ZP, draw.Src)
		}
	}

	err = png.Encode(out, img)
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
		os.Exit(2)
	}

	fmt.Printf("Wrote random image to \"%s\"\n", *outfile)
	os.Exit(0)
}

示例#20
文件: water_marker.go 项目: nivance/go-example

func cmd_watermark(file string, to string, logo string) {
	// 打开图片并解码
	file_origin, _ := os.Open(file)
	origin, _ := jpeg.Decode(file_origin)
	defer file_origin.Close()

	// 打开水印图并解码
	file_watermark, _ := os.Open(logo)
	watermark, _ := png.Decode(file_watermark)
	defer file_watermark.Close()

	offset := image.Pt(origin.Bounds().Dx()-watermark.Bounds().Dx()-10, origin.Bounds().Dy()-watermark.Bounds().Dy()-10)

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

	//创建新图层
	canvas := image.NewNRGBA(origin_size)
	// 贴原始图
	draw.Draw(canvas, origin_size, origin, image.ZP, draw.Src)
	// 贴水印图
	draw.Draw(canvas, watermark.Bounds().Add(offset), watermark, image.ZP, draw.Over)

	//生成新图片
	create_image, _ := os.Create(to)
	jpeg.Encode(create_image, canvas, &jpeg.Options{85})
	defer create_image.Close()
}

示例#21
文件: directlyCreateGIF.go 项目: muralibalki/learnGO

func writeToJP() {

	imgRect := image.Rect(0, 0, gridSize*10, gridSize*10)
	img := image.NewGray(imgRect)
	draw.Draw(img, img.Bounds(), &image.Uniform{color.White}, image.ZP, draw.Src)
	for x := 0; x < gridSize; x++ {
		for y := 0; y < gridSize; y++ {
			fill := &image.Uniform{color.White}
			if Env[x][y] == -1 {
				fill = &image.Uniform{color.Black}
			} else if Env[x][y] > 1 {
				c := color.Gray{uint8(Env[x][y] * 20)}
				fill = &image.Uniform{c}
			}

			draw.Draw(img, image.Rect((x-1)*10, (y-1)*10, x*10, y*10), fill, image.ZP, draw.Src)
		}
	}
	buf := bytes.Buffer{}
	// ok, write out the data into the new JPEG file
	err := gif.Encode(&buf, img, nil)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	tmpimg, err := gif.Decode(&buf)
	if err != nil {
		log.Printf("Skipping frame due to weird error reading the temporary gif :%s", err)
	}
	frames = append(frames, tmpimg.(*image.Paletted))
}

示例#22
文件: encoderbackground.go 项目: jmdkina/jkgo

func main() {
	//原始<strong><strong>图片</strong></strong>是sam.jpg
	imgb, _ := os.Open("sam.jpg")
	img, _ := jpeg.Decode(imgb)
	defer imgb.Close()

	wmb, _ := os.Open("text.png")
	watermark, _ := png.Decode(wmb)
	defer wmb.Close()

	//把<strong><strong>水印</strong></strong>写到右下角,并向0坐标各偏移10个像素
	offset := image.Pt(img.Bounds().Dx()-watermark.Bounds().Dx()-10, img.Bounds().Dy()-watermark.Bounds().Dy()-10)
	b := img.Bounds()
	m := image.NewNRGBA(b)

	draw.Draw(m, b, img, image.ZP, draw.Src)
	draw.Draw(m, watermark.Bounds().Add(offset), watermark, image.ZP, draw.Over)

	//生成新<strong><strong>图片</strong></strong>new.jpg,并设置<strong><strong>图片</strong></strong>质量..
	imgw, _ := os.Create("new.jpg")
	jpeg.Encode(imgw, m, &jpeg.Options{100})

	defer imgw.Close()

	fmt.Println("<strong><strong>水印</strong></strong>添加结束,请查看new.jpg<strong><strong>图片</strong></strong>...")
}

示例#23
文件: colorblend.go 项目: ReshNesh/go-colorful

func main() {
	blocks := 10
	blockw := 40
	img := image.NewRGBA(image.Rect(0, 0, blocks*blockw, 200))

	c1, _ := colorful.Hex("#fdffcc")
	c2, _ := colorful.Hex("#242a42")

	// Use these colors to get invalid RGB in the gradient.
	//c1, _ := colorful.Hex("#EEEF61")
	//c2, _ := colorful.Hex("#1E3140")

	for i := 0; i < blocks; i++ {
		draw.Draw(img, image.Rect(i*blockw, 0, (i+1)*blockw, 40), &image.Uniform{c1.BlendHsv(c2, float64(i)/float64(blocks-1))}, image.ZP, draw.Src)
		draw.Draw(img, image.Rect(i*blockw, 40, (i+1)*blockw, 80), &image.Uniform{c1.BlendLuv(c2, float64(i)/float64(blocks-1))}, image.ZP, draw.Src)
		draw.Draw(img, image.Rect(i*blockw, 80, (i+1)*blockw, 120), &image.Uniform{c1.BlendRgb(c2, float64(i)/float64(blocks-1))}, image.ZP, draw.Src)
		draw.Draw(img, image.Rect(i*blockw, 120, (i+1)*blockw, 160), &image.Uniform{c1.BlendLab(c2, float64(i)/float64(blocks-1))}, image.ZP, draw.Src)
		draw.Draw(img, image.Rect(i*blockw, 160, (i+1)*blockw, 200), &image.Uniform{c1.BlendHcl(c2, float64(i)/float64(blocks-1))}, image.ZP, draw.Src)

		// This can be used to "fix" invalid colors in the gradient.
		//draw.Draw(img, image.Rect(i*blockw,160,(i+1)*blockw,200), &image.Uniform{c1.BlendHcl(c2, float64(i)/float64(blocks-1)).Clamped()}, image.ZP, draw.Src)
	}

	toimg, err := os.Create("colorblend.png")
	if err != nil {
		fmt.Printf("Error: %v", err)
		return
	}
	defer toimg.Close()

	png.Encode(toimg, img)
}

示例#24
文件: application.go 项目: danielf/danielabs

func detectFace(input *image.Image, multiple bool) (*bytes.Buffer, error) {
	daniel := opencv.LoadImage("static/daniel.jpg").ToImage()
	hdaniel := int(daniel.Bounds().Dy())
	wdaniel := int(daniel.Bounds().Dx())
	_image := opencv.FromImage(*input)
	cascade := opencv.LoadHaarClassifierCascade("haarcascade_frontalface_alt.xml")
	faces := cascade.DetectObjects(_image)
	found := false
	bounds := (*input).Bounds()
	output := image.NewRGBA(bounds)
	draw.Draw(output, bounds, *input, image.ZP, draw.Src)
	for _, value := range faces {
		x := int(value.X())
		y := int(value.Y())
		w := int(value.Width())
		h := int(value.Height())
		y2 := y + h
		h = hdaniel * w / wdaniel
		y = y2 - h
		danielTmp := resize.Resize(uint(w), uint(h), daniel, resize.Lanczos3)
		if multiple || !found {
			draw.Draw(output, image.Rect(x, y, x+w, y+h), danielTmp, image.ZP, draw.Src)
		}
		found = true
	}
	if !found {
		return nil, errors.New("No faces found")
	}
	toOut := new(bytes.Buffer)
	err := jpeg.Encode(toOut, output, nil)
	if err != nil {
		return nil, err
	}
	return toOut, nil
}

示例#25
文件: imagetest.go 项目: remogatto/imagetest

// Adjust adjusts the two images aligning ther centers. The background
// of the smaller image is filled with FillColor. The returned images
// are of the same size.
func (c Centerer) Adjust(img1, img2 image.Image) (image.Image, image.Image) {
	img1Rect := img1.Bounds()
	img2Rect := img2.Bounds()
	backgroundRect := img1Rect.Union(img2Rect)

	dstImg1 := image.NewRGBA(backgroundRect)
	dstImg2 := image.NewRGBA(backgroundRect)

	// Fill destination images with FillColor
	draw.Draw(dstImg1, dstImg1.Bounds(), &image.Uniform{c.FillColor}, image.ZP, draw.Src)
	draw.Draw(dstImg2, dstImg2.Bounds(), &image.Uniform{c.FillColor}, image.ZP, draw.Src)

	// Copy img1 to the center of dstImg1
	dp := image.Point{
		(backgroundRect.Max.X-backgroundRect.Min.X)/2 - (img1Rect.Max.X-img1Rect.Min.X)/2,
		(backgroundRect.Max.Y-backgroundRect.Min.Y)/2 - (img1Rect.Max.Y-img1Rect.Min.Y)/2,
	}
	r := image.Rectangle{dp, dp.Add(img1Rect.Size())}
	draw.Draw(dstImg1, r, img1, image.ZP, draw.Src)

	// Copy img2 to the center of dstImg2
	dp = image.Point{
		(backgroundRect.Max.X-backgroundRect.Min.X)/2 - (img2Rect.Max.X-img2Rect.Min.X)/2,
		(backgroundRect.Max.Y-backgroundRect.Min.Y)/2 - (img2Rect.Max.Y-img2Rect.Min.Y)/2,
	}
	r = image.Rectangle{dp, dp.Add(img2Rect.Size())}
	draw.Draw(dstImg2, r, img2, image.ZP, draw.Src)

	return dstImg1, dstImg2
}

示例#26
文件: utils.go 项目: jabrena/skymapper

func CreateDigitalImage(imagePath string) {

	//Create an image object with some dimensions
	img := image.NewRGBA(image.Rect(0, 0, imageWidth, imageHeight))

	//Define colors used in the digital examples
	white := color.RGBA{uint8(255), uint8(255), uint8(255), uint8(255)}
	red := color.RGBA{uint8(255), uint8(0), uint8(0), uint8(255)}

	//Add a white background.
	draw.Draw(img, image.Rect(0, 0, imageWidth, imageHeight), &image.Uniform{white}, image.ZP, draw.Src)

	//Add some red blobs.
	draw.Draw(img, image.Rect(50, 50, 55, 55), &image.Uniform{red}, image.ZP, draw.Src)

	toimg, err := os.Create("digitalImage.png")
	if err != nil {
		fmt.Printf("Error: %v", err)
		return
	}
	defer toimg.Close()

	png.Encode(toimg, img)

}

示例#27
文件: fontface.go 项目: kurrik/opengl-benchmarks

func (ff *FontFace) GetImage(text string) (img draw.Image, err error) {
	var (
		src image.Image
		bg  image.Image
		dst draw.Image
		pt  fixed.Point26_6
		w   int
		h   int
	)
	src = image.NewUniform(ff.fg)
	bg = image.NewUniform(ff.bg)
	w = int(float32(len(text)) * ff.charw)
	h = int(ff.charh)
	dst = image.NewRGBA(image.Rect(0, 0, w, h))
	draw.Draw(dst, dst.Bounds(), bg, image.ZP, draw.Src)
	ff.context.SetSrc(src)
	ff.context.SetDst(dst)
	ff.context.SetClip(dst.Bounds())
	pt = freetype.Pt(0, int(ff.charh+ff.offy))
	if pt, err = ff.context.DrawString(text, pt); err != nil {
		return
	}
	img = image.NewRGBA(image.Rect(0, 0, int(pt.X/64), int(pt.Y/64)))
	draw.Draw(img, img.Bounds(), dst, image.Pt(0, -int(ff.offy)), draw.Src)
	return
}

示例#28
文件: text.go 项目: pikkpoiss/twodee

func (ff *FontFace) GetText(text string) (t *Texture, err error) {
	var (
		src       image.Image
		bg        image.Image
		dst       draw.Image
		shortened draw.Image
		pt        fixed.Point26_6
		w         int
		h         int
	)
	src = image.NewUniform(ff.fg)
	bg = image.NewUniform(ff.bg)
	w = int(float32(len(text)) * ff.charw)
	h = int(ff.charh)
	dst = image.NewRGBA(image.Rect(0, 0, w, h))
	draw.Draw(dst, dst.Bounds(), bg, image.ZP, draw.Src)
	ff.context.SetSrc(src)
	ff.context.SetDst(dst)
	ff.context.SetClip(dst.Bounds())
	pt = freetype.Pt(0, int(ff.charh))
	if pt, err = ff.context.DrawString(text, pt); err != nil {
		return
	}
	// if err = WritePNG("hello.png", dst); err != nil {
	// 	return
	// }
	shortened = image.NewRGBA(image.Rect(0, 0, int(pt.X/64), h))
	draw.Draw(shortened, shortened.Bounds(), dst, image.ZP, draw.Src)
	t, err = GetTexture(shortened, gl.NEAREST)
	return
}

示例#29
文件: extract.go 项目: cwren/squid

func main() {
	flag.Parse()

	reader, err := os.Open(*in)
	if err != nil {
		log.Fatal(err)
	}
	defer reader.Close()

	i, _, err := image.Decode(reader)
	if err != nil {
		log.Fatal(err)
	}
	b := i.Bounds()
	m := image.NewGray(b) // monochrome
	draw.Draw(m, b, i, b.Min, draw.Src)

	o := image.NewGray(image.Rect(0, 0, 256, 256))
	white := color.RGBA{0xff, 0xff, 0xff, 0xff}
	black := color.RGBA{0x00, 0x00, 0x00, 0xff}
	draw.Draw(o, o.Bounds(), &image.Uniform{white}, image.ZP, draw.Src)

	delta := []int{-16, -1, 1, 16}
	ud := []int{-6, 0, 0, 6}
	lr := []int{0, -6, 6, 0}
	for j := 0; j < 16; j++ {
		for i := 0; i < 16; i++ {
			cx := int(19 + 20.5333*float64(i))
			cy := int(19 + 20.5333*float64(j))
			s := []uint32{0, 0, 0, 0}
			best := uint32(50000)
			bestK := 0
			for k := 0; k < 4; k++ {
				for sx := -1; sx < 2; sx++ {
					for sy := -1; sy < 2; sy++ {
						r, g, b, _ := m.At(cx+lr[k]+sx, cy+ud[k]+sy).RGBA()
						s[k] += (r + g + b) / 3
					}
				}
				if k == 0 || s[k] < best {
					best = s[k]
					bestK = k
				}
			}

			src := 16*j + i
			dst := (src + delta[bestK] + 256) % 256
			fmt.Printf("%v\n", dst)
			o.Set(src, dst, black)
		}
	}

	writer, err := os.Create(*out)
	if err != nil {
		log.Fatal(err)
	}

	png.Encode(writer, o)
	writer.Close()
}

示例#30
文件: main.go 项目: otiai10/amesh

func main() {

	if daemon {
		startDaemon()
		return
	}

	entry := amesh.GetEntry()

	meshLayer, err := getImage(entry.Mesh)
	onerror(err)

	base := image.NewRGBA(meshLayer.Bounds())

	if geo {
		geoLayer, err := getImage(entry.Map)
		onerror(err)
		draw.Draw(base, base.Bounds(), geoLayer, image.Point{0, 0}, 0)
	}

	draw.Draw(base, meshLayer.Bounds(), meshLayer, image.Point{0, 0}, 0)

	if mesh {
		mapLayer, err := getImage(entry.Mask)
		onerror(err)
		draw.Draw(base, base.Bounds(), mapLayer, image.Point{0, 0}, 0)
	}

	gat.NewClient(gat.GetTerminal()).Set(gat.SimpleBorder{}).PrintImage(base)
	fmt.Println("#amesh", entry.URL)
}

展开阅读全文