Пример #1
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()
}
Пример #2
1
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
	}

}
Пример #3
0
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()
}
Пример #4
0
// 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
}
Пример #5
0
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)
}
Пример #6
0
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)
}
Пример #7
0
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)
}
Пример #8
0
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)
}
Пример #9
0
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()
	}
}
Пример #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
	})
}
Пример #11
0
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)
		}

	}

}
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))
}
Пример #13
0
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()
		}()
	}
}
Пример #14
0
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
}
Пример #15
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 {
	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()
}
Пример #16
0
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()
}
Пример #17
0
func kartaPNGHandler(c *context, r *http.Request, w http.ResponseWriter) error {
	if r.Method != "GET" {
		return errors.New("no such handler")
	}

	seed := getInt(r, "s", 3, 0, math.MaxUint32)
	width := getInt(r, "w", 512, 10, 5120)
	height := getInt(r, "h", 512, 10, 5120)
	count := getInt(r, "c", 2048, 3, 10000)
	iterations := getInt(r, "i", 1, 0, 16)

	// Seed the random number generator
	rand.Seed(int64(seed))

	// Create a new karta
	k := karta.New(width, height, count, iterations)

	if k.Generate() == nil {
		w.Header().Add("Content-Type", "image/png")

		err := png.Encode(w, k.Image)
		if err != nil {
			return err
		}

		c.logf("Served PNG count=%v width=%v height=%v iterations=%v seed=%v",
			count, width, height, iterations, seed)
	} else {
		return errors.New("could not generate image")
	}

	return nil
}
Пример #18
0
func writeImageToFile(t *testing.T, img image.Image, dstFilename string, fileFmt string,
	bmpOpts *EncoderOptions) {
	var err error

	file, err := os.Create(dstFilename)
	if err != nil {
		t.Logf("%s\n", err.Error())
		t.FailNow()
		return
	}
	defer file.Close()

	if fileFmt == "png" {
		err = png.Encode(file, img)
	} else {
		if bmpOpts != nil {
			err = EncodeWithOptions(file, img, bmpOpts)
		} else {
			err = Encode(file, img)
		}
	}
	if err != nil {
		t.Logf("%s\n", err.Error())
		t.FailNow()
		return
	}
}
Пример #19
0
func main() {
	const maxX = 1024
	const maxY = 800

	const centerRe, centerIm float64 = -0.7435669, 0.1314023
	const hd float64 = 0.0022878
	const hv float64 = float64(maxY) / float64(maxX) * hd

	const hdStepX = hd / maxX
	const hdStepY = hv / maxY

	const upperLeftRe = centerRe - (float64(maxX/2) * hdStepX)
	const upperLeftIm = centerIm - (float64(maxY/2) * hdStepY)

	f, err := os.Create("mandel.png")
	if err != nil {
		panic(err)
	}
	m := image.NewRGBA(image.Rect(0, 0, maxX, maxY))
	b := m.Bounds()
	for y := b.Min.Y; y < b.Max.Y; y++ {
		for x := b.Min.X; x < b.Max.X; x++ {
			dx := float64(x) * hdStepX
			dy := float64(y) * hdStepY
			iter := mandel.Iterate(upperLeftRe+dx, upperLeftIm+dy, 1024)
			c := getColor(iter)
			m.Set(x, maxY-y, c)
		}
	}

	if err = png.Encode(f, m); err != nil {
		panic(err)
	}
}
Пример #20
0
func TestEncode(t *testing.T) {
	img := prepareImg(t)
	buf := &bytes.Buffer{}
	if err := png.Encode(buf, img); err != nil {
		t.Fatal(err)
	}

	imgGo, _, err := image.Decode(buf)
	if err != nil {
		t.Fatal(err)
	}

	assertEqual(t, img.Bounds(), imgGo.Bounds())

	b, err := Encode(img, "png")
	if err != nil {
		t.Fatal(err)
	}

	imgMapnik, _, err := image.Decode(bytes.NewReader(b))
	if err != nil {
		t.Fatal(err)
	}

	assertImageEqual(t, img, imgMapnik)
	assertImageEqual(t, imgGo, imgMapnik)
}
Пример #21
0
func createImage(iterations uint32, degree float64, factor float64) {
	// Declare image size
	width, height := 2048, 1024

	// Create a new image
	img := image.Rect(0, 0, width, height)
	c := NewCanvas(img)
	c.DrawGradient()

	rand.Seed(time.Now().UTC().UnixNano())
	for i := 0; i < 300; i++ {
		x := float64(width) * rand.Float64()
		y := float64(height) * rand.Float64()
		color := color.RGBA{uint8(rand.Intn(255)),
			uint8(rand.Intn(255)),
			uint8(rand.Intn(255)),
			255}
		c.DrawSpiral(color, Coordinate{x, y}, iterations, degree, factor)
	}

	name := fmt.Sprintf("spiral_%d_%f_%f.png", iterations, degree, factor)
	file, err := os.Create(name)
	if err != nil {
		log.Fatal(err)
	}

	defer file.Close()
	png.Encode(file, c)
}
Пример #22
0
func main() {
	if len(os.Args) != 2 {
		fmt.Println("./ex08 [64|128] > result.png")
		os.Exit(1)
	}
	const (
		xmin, ymin, xmax, ymax = -2, -2, +2, +2
		width, height          = 1024, 1024
	)

	img := image.NewRGBA(image.Rect(0, 0, width, height))
	for py := 0; py < height; py++ {
		y := float64(py)/height*(ymax-ymin) + ymin
		for px := 0; px < width; px++ {
			x := float64(px)/width*(xmax-xmin) + xmin
			z := complex(x, y)
			// Image point (px, py) represents complex value z.
			switch os.Args[1] {
			case "64":
				img.Set(px, py, mandelbrot64(complex64(z)))
			case "128":
				img.Set(px, py, mandelbrot128(z))
			default:
				fmt.Println("./ex08 [64|128]")
				os.Exit(1)
			}
		}
	}
	png.Encode(os.Stdout, img) // NOTE: ignoring errors
}
Пример #23
0
func Write() {
	err := png.Encode(PngFile, Pixels)
	if err != nil {
		fmt.Println(err)
	}
	// following line encodes pixel data only, not full png file
	fi0, err := PngFile.Stat()
	if err != nil {
		fmt.Println(err)
	}
	d1 := make([]byte, fi0.Size())
	_, err = PngFile.Seek(0, 0)
	if err != nil {
		fmt.Println(err)
	}
	_, err = PngFile.Read(d1)
	if err != nil {
		fmt.Println(err)
	}
	s0 := base64.StdEncoding.EncodeToString(d1)
	s1 := "data:image/png;base64,"
	s2 := fmt.Sprintf("%s%s", s1, s0)
	d0 := Favio{DataUri: s2}
	b0, err := json.Marshal(d0)
	if err != nil {
		fmt.Println(err)
	}
	_, err = JsonFile.Write(b0)
	if err != nil {
		fmt.Println(err)
	}

}
Пример #24
0
func Example() {
	// As usual in examples, this ignores all errors. Don't do this in your program.

	// setup and find start point for centering
	s := "Hello, World!"
	size := image.Rect(0, 0, 120, 20)
	dst := image.NewRGBA(size)
	c := freetype.NewContext()
	c.SetFont(font)
	c.SetFontSize(14.0)
	c.SetSrc(image.NewUniform(color.Black))
	c.SetDst(dst)
	start, _ := fontutil.CenterX(c, s, size) // CenterX calls c.SetClip(size)

	// perform draw at start.X + y 16
	c.DrawString(s, start.Add(freetype.Pt(0, 16)))

	// write the image out to a file
	// out, _ := os.Create("helloworld.png")
	// defer out.Close()

	// write image to hash for testing purposes
	out := fnv.New64()
	_ = png.Encode(out, dst)
	fmt.Printf("Hash of compressed image: %x", out.Sum64())
	// Output: Hash of compressed image: fa83a1b8d8abf5f2
}
Пример #25
0
func main() {
	flag.Parse()

	if *seed == 0 {
		*seed = time.Now().UnixNano()
		fmt.Println("seed", *seed)
	}

	interp := perlin.CosInterp
	if *linInterp {
		interp = perlin.LinearInterp
	}

	noise := perlin.Make(*persist, *scale, *noct, *seed, interp)
	img := makeNoiseImg(*width, *height, noise)

	f, err := os.Create(*outpath)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	if err := png.Encode(f, img); err != nil {
		panic(err)
	}
}
Пример #26
0
// encodedPNG encodes an image to PNG and returns
// the result as a byte slice.
func (m *Image) encodedPNG() []byte {
	var buf bytes.Buffer
	if err := png.Encode(&buf, m.Paletted); err != nil {
		panic(err.Error())
	}
	return buf.Bytes()
}
Пример #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
}
Пример #28
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 = png.Encode(fw, img); err != nil {
		return fmt.Errorf("Encode: %v", err)
	}

	log.Info("New random avatar created: %d", u.ID)
	return nil
}
Пример #29
0
func main() {
	f, err := os.Open("Pentagon.png")
	if err != nil {
		fmt.Println(err)
		return
	}
	pent, err := png.Decode(f)
	if err != nil {
		fmt.Println(err)
		return
	}
	if err = f.Close(); err != nil {
		fmt.Println(err)
	}
	h := hough(pent, 460, 360)
	if f, err = os.Create("hough.png"); err != nil {
		fmt.Println(err)
		return
	}
	if err = png.Encode(f, h); err != nil {
		fmt.Println(err)
	}
	if cErr := f.Close(); cErr != nil && err == nil {
		fmt.Println(err)
	}
}
Пример #30
0
func (i TestImage) write(data image.Image) {
	outfile, err := os.Create(string(i))
	Expect(err).NotTo(HaveOccurred())
	defer outfile.Close()

	png.Encode(outfile, data)
}