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) }
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 }
func TestEncodeAllFramesOutOfBounds(t *testing.T) { images := []*image.Paletted{ image.NewPaletted(image.Rect(0, 0, 5, 5), palette.Plan9), image.NewPaletted(image.Rect(2, 2, 8, 8), palette.Plan9), image.NewPaletted(image.Rect(3, 3, 4, 4), palette.Plan9), } for _, upperBound := range []int{6, 10} { g := &GIF{ Image: images, Delay: make([]int, len(images)), Disposal: make([]byte, len(images)), Config: image.Config{ Width: upperBound, Height: upperBound, }, } err := EncodeAll(ioutil.Discard, g) if upperBound >= 8 { if err != nil { t.Errorf("upperBound=%d: %v", upperBound, err) } } else { if err == nil { t.Errorf("upperBound=%d: got nil error, want non-nil", upperBound) } } } }
func TestDrawOverlap(t *testing.T) { for _, op := range []Op{Over, Src} { for yoff := -2; yoff <= 2; yoff++ { loop: for xoff := -2; xoff <= 2; xoff++ { m := gradYellow(127).(*image.RGBA) dst := m.SubImage(image.Rect(5, 5, 10, 10)).(*image.RGBA) src := m.SubImage(image.Rect(5+xoff, 5+yoff, 10+xoff, 10+yoff)).(*image.RGBA) b := dst.Bounds() // Draw the (src, mask, op) onto a copy of dst using a slow but obviously correct implementation. golden := makeGolden(dst, b, src, src.Bounds().Min, nil, image.ZP, op) if !b.Eq(golden.Bounds()) { t.Errorf("drawOverlap xoff=%d,yoff=%d: bounds %v versus %v", xoff, yoff, dst.Bounds(), golden.Bounds()) continue } // Draw the same combination onto the actual dst using the optimized DrawMask implementation. DrawMask(dst, b, src, src.Bounds().Min, nil, image.ZP, op) // Check that the resultant dst image matches the golden output. for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { if !eq(dst.At(x, y), golden.At(x, y)) { t.Errorf("drawOverlap xoff=%d,yoff=%d: at (%d, %d), %v versus golden %v", xoff, yoff, x, y, dst.At(x, y), golden.At(x, y)) continue loop } } } } } } }
func rotate(im image.Image, angle int) image.Image { var rotated *image.NRGBA // trigonometric (i.e counter clock-wise) switch angle { case 90: newH, newW := im.Bounds().Dx(), im.Bounds().Dy() rotated = image.NewNRGBA(image.Rect(0, 0, newW, newH)) for y := 0; y < newH; y++ { for x := 0; x < newW; x++ { rotated.Set(x, y, im.At(newH-1-y, x)) } } case -90: newH, newW := im.Bounds().Dx(), im.Bounds().Dy() rotated = image.NewNRGBA(image.Rect(0, 0, newW, newH)) for y := 0; y < newH; y++ { for x := 0; x < newW; x++ { rotated.Set(x, y, im.At(y, newW-1-x)) } } case 180, -180: newW, newH := im.Bounds().Dx(), im.Bounds().Dy() rotated = image.NewNRGBA(image.Rect(0, 0, newW, newH)) for y := 0; y < newH; y++ { for x := 0; x < newW; x++ { rotated.Set(x, y, im.At(newW-1-x, newH-1-y)) } } default: return im } return rotated }
func TestLoadConfig(t *testing.T) { var sampleFile = "../_template/furnace.toml" var answer = Config{ Type: "furnace", Image: "furnace.png", Crop: image.Rect(7, 6, 168, 79), Slot: []image.Point{ {56, 53}, {56, 17}, {116, 35}, }, Progress: []Progress{ { Crop: image.Rect(176, 0, 189, 13), Paste: image.Pt(57, 36), }, { Crop: image.Rect(176, 14, 24, 17), Paste: image.Pt(199, 30), }, }, } sample := sampleFile ans := answer if !reflect.DeepEqual(LoadConfig(sample), ans) { t.Error("toml convert error: not equal input and output \n", LoadConfig(sample), ans) } }
func TestSrcMask(t *testing.T) { srcMask := image.NewRGBA(image.Rect(0, 0, 23, 1)) srcMask.SetRGBA(19, 0, color.RGBA{0x00, 0x00, 0x00, 0x7f}) srcMask.SetRGBA(20, 0, color.RGBA{0x00, 0x00, 0x00, 0xff}) srcMask.SetRGBA(21, 0, color.RGBA{0x00, 0x00, 0x00, 0x3f}) srcMask.SetRGBA(22, 0, color.RGBA{0x00, 0x00, 0x00, 0x00}) red := image.NewUniform(color.RGBA{0xff, 0x00, 0x00, 0xff}) blue := image.NewUniform(color.RGBA{0x00, 0x00, 0xff, 0xff}) dst := image.NewRGBA(image.Rect(0, 0, 6, 1)) Copy(dst, image.Point{}, blue, dst.Bounds(), Src, nil) NearestNeighbor.Scale(dst, dst.Bounds(), red, image.Rect(0, 0, 3, 1), Over, &Options{ SrcMask: srcMask, SrcMaskP: image.Point{20, 0}, }) got := [6]color.RGBA{ dst.RGBAAt(0, 0), dst.RGBAAt(1, 0), dst.RGBAAt(2, 0), dst.RGBAAt(3, 0), dst.RGBAAt(4, 0), dst.RGBAAt(5, 0), } want := [6]color.RGBA{ {0xff, 0x00, 0x00, 0xff}, {0xff, 0x00, 0x00, 0xff}, {0x3f, 0x00, 0xc0, 0xff}, {0x3f, 0x00, 0xc0, 0xff}, {0x00, 0x00, 0xff, 0xff}, {0x00, 0x00, 0xff, 0xff}, } if got != want { t.Errorf("\ngot %v\nwant %v", got, want) } }
func parseImgBoundary(img image.Image) { minX, maxX := img.Bounds().Min.X, img.Bounds().Max.X minY, maxY := img.Bounds().Min.Y, img.Bounds().Max.Y for i := minX; i < maxX; i++ { for j := minY; j < maxY; j++ { _, _, _, a := img.At(i, j).RGBA() if a != 0 { if boundary.Empty() && boundary.Min.X == -1 { boundary = image.Rect(i, j, i, j) } else { _p := image.Point{i, j} if !_p.In(boundary) { boundary = boundary.Union(image.Rect(i, j, i, j)) } } } } } // Should Make the midline of boundary and the img l := boundary.Min.X r := imageW - boundary.Max.X if l > r { boundary.Min.X = r } else if l < r { boundary.Max.X = imageW - l } }
//------------------------------------------------------------------------------ // Image Functions func mergeImage(imgs []image.Image) image.Image { width := 0 height := 0 imgs[0] = RotateImageLeft(imgs[0]) for _, v := range imgs { if v.Bounds().Size().X > width { width = v.Bounds().Size().X } height += v.Bounds().Size().Y } m := image.NewRGBA(image.Rect(0, 0, width, height)) height = 0 for _, v := range imgs { h := v.Bounds().Size().Y draw.Draw(m, image.Rect(0, height, v.Bounds().Size().X, h+height), v, v.Bounds().Min, draw.Src) height += h } return m }
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 }
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)) }
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) }
func TestRotate270(t *testing.T) { td := []struct { desc string src image.Image want *image.NRGBA }{ { "Rotate270 2x3", &image.NRGBA{ Rect: image.Rect(-1, -1, 1, 2), Stride: 2 * 4, Pix: []uint8{ 0x00, 0x11, 0x22, 0x33, 0xcc, 0xdd, 0xee, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, }, }, &image.NRGBA{ Rect: image.Rect(0, 0, 3, 2), Stride: 3 * 4, Pix: []uint8{ 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0xcc, 0xdd, 0xee, 0xff, }, }, }, } for _, d := range td { got := Rotate270(d.src) want := d.want if !compareNRGBA(got, want, 0) { t.Errorf("test [%s] failed: %#v", d.desc, got) } } }
// Join the matrix of images into a single image. func (h Himawari) joinGrid(grid [][]image.Image) image.Image { dst := image.NewNRGBA(image.Rect(0, 0, gridSize*h.Depth, gridSize*h.Depth)) var wg sync.WaitGroup for i := range grid { for j := range grid[i] { if grid[i][j] == nil { break } wg.Add(1) go func(i, j int) { defer wg.Done() // Modification is performed pixel-by-pixel, so async // should be fine, theoretically. src := grid[i][j] sdx, sdy := src.Bounds().Dx(), src.Bounds().Dy() rect := image.Rect( i*sdx, j*sdy, i*sdx+sdx, j*sdy+sdy, ) draw.Draw(dst, rect, src, image.ZP, draw.Src) }(i, j) } } wg.Wait() return dst }
// DrawText is a convenience function that will create a new image, render // the provided text to it, paint the image to the provided window, and resize // the window to fit the text snugly. // // An error can occur when rendering the text to an image. func DrawText(win *xwindow.Window, font *truetype.Font, size float64, fontClr, bgClr color.RGBA, text string) error { // Over estimate the extents. ew, eh := xgraphics.TextMaxExtents(font, size, text) eh += misc.TextBreathe // <-- this is the bug // Create an image using the over estimated extents. img := xgraphics.New(win.X, image.Rect(0, 0, ew, eh)) xgraphics.BlendBgColor(img, bgClr) // Now draw the text, grab the (x, y) position advanced by the text, and // check for an error in rendering. x, y, err := img.Text(0, 0, fontClr, size, font, text) if err != nil { return err } // Resize the window to the geometry determined by (x, y). w, h := x, y+misc.TextBreathe // <-- also part of the bug win.Resize(w, h) // Now draw the image to the window and destroy it. img.XSurfaceSet(win.Id) subimg := img.SubImage(image.Rect(0, 0, w, h)) subimg.XDraw() subimg.XPaint(win.Id) img.Destroy() return nil }
// makeImg allocates and initializes the destination image. func (d *decoder) makeImg(h0, v0, mxx, myy int) { if d.nComp == nGrayComponent { d.img1 = image.NewGray(8*mxx, 8*myy) d.img1.Rect = image.Rect(0, 0, d.width, d.height) return } var subsampleRatio ycbcr.SubsampleRatio n := h0 * v0 switch n { case 1: subsampleRatio = ycbcr.SubsampleRatio444 case 2: subsampleRatio = ycbcr.SubsampleRatio422 case 4: subsampleRatio = ycbcr.SubsampleRatio420 default: panic("unreachable") } b := make([]byte, mxx*myy*(1*8*8*n+2*8*8)) d.img3 = &ycbcr.YCbCr{ Y: b[mxx*myy*(0*8*8*n+0*8*8) : mxx*myy*(1*8*8*n+0*8*8)], Cb: b[mxx*myy*(1*8*8*n+0*8*8) : mxx*myy*(1*8*8*n+1*8*8)], Cr: b[mxx*myy*(1*8*8*n+1*8*8) : mxx*myy*(1*8*8*n+2*8*8)], SubsampleRatio: subsampleRatio, YStride: mxx * 8 * h0, CStride: mxx * 8, Rect: image.Rect(0, 0, d.width, d.height), } }
func TestRotate270(t *testing.T) { img0 := image.NewGray(image.Rect(-1, -1, 3, 1)) img0.Pix = []uint8{ 1, 2, 3, 4, 5, 6, 7, 8, } img1Exp := image.NewGray(image.Rect(0, 0, 2, 4)) img1Exp.Pix = []uint8{ 5, 1, 6, 2, 7, 3, 8, 4, } f := Rotate270() img1 := image.NewGray(f.Bounds(img0.Bounds())) f.Draw(img1, img0, nil) if img1.Bounds().Size() != img1Exp.Bounds().Size() { t.Errorf("expected %v got %v", img1Exp.Bounds().Size(), img1.Bounds().Size()) } if !comparePix(img1Exp.Pix, img1.Pix) { t.Errorf("expected %v got %v", img1Exp.Pix, img1.Pix) } }
func (p *Page) concatImages() error { width := 0 height := 0 for _, i := range p.divImages { img, err := utility.DecodeImage(i) if err != nil { return err } height += img.Bounds().Size().Y if width < img.Bounds().Size().X { width = img.Bounds().Size().X } } dstRect := image.Rect(0, 0, width, height) dstImage := image.NewRGBA(dstRect) top := 0 for _, i := range p.divImages { img, err := utility.DecodeImage(i) if err != nil { return err } srcPoint := image.Point{0, 0} dstRect := image.Rect(0, top, img.Bounds().Size().X, top+img.Bounds().Size().Y) draw.Draw(dstImage, dstRect, img, srcPoint, draw.Src) top += img.Bounds().Size().Y } return utility.SaveImage(dstImage, p.imagePath()) }
// TestNegativeWeights tests that scaling by a kernel that produces negative // weights, such as the Catmull-Rom kernel, doesn't produce an invalid color // according to Go's alpha-premultiplied model. func TestNegativeWeights(t *testing.T) { check := func(m *image.RGBA) error { b := m.Bounds() for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { if c := m.RGBAAt(x, y); c.R > c.A || c.G > c.A || c.B > c.A { return fmt.Errorf("invalid color.RGBA at (%d, %d): %v", x, y, c) } } } return nil } src := image.NewRGBA(image.Rect(0, 0, 16, 16)) for y := 0; y < 16; y++ { for x := 0; x < 16; x++ { a := y * 0x11 src.Set(x, y, color.RGBA{ R: uint8(x * 0x11 * a / 0xff), A: uint8(a), }) } } if err := check(src); err != nil { t.Fatalf("src image: %v", err) } dst := image.NewRGBA(image.Rect(0, 0, 32, 32)) CatmullRom.Scale(dst, dst.Bounds(), src, src.Bounds(), Over, nil) if err := check(dst); err != nil { t.Fatalf("dst image: %v", err) } }
func txNavRun(c *cmdapp.Command, args []string) { cmd = c var db jdh.DB if len(extDBFlag) != 0 { openExt(c, extDBFlag, "") db = extDB } else { openLocal(c) db = localDB } title := fmt.Sprintf("%s: please wait", c.Name) m := widget.NewMainWindow("main", title) geo := m.Property(sparta.Geometry).(image.Rectangle) widget.NewButton(m, "upTax", "up", image.Rect(5, 5, 5+(sparta.WidthUnit*10), 5+(3*sparta.HeightUnit/2))) tx := widget.NewCanvas(m, "info", image.Rect(210, 10+(3*sparta.HeightUnit/2), geo.Dx()-10, geo.Dy()-10)) tx.SetProperty(sparta.Border, true) tx.Capture(sparta.Expose, txNavInfoExpose) wnd["info"] = tx l := widget.NewList(m, "taxonList", image.Rect(5, 10+(3*sparta.HeightUnit/2), 200, geo.Dy()-10)) wnd["taxonList"] = l m.Capture(sparta.Configure, txNavConf) m.Capture(sparta.Command, txNavComm) sparta.Block(nil) go txNavInitList(m, l, db, nil, 0) sparta.Run() }
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 }
// Thumbnail scales and crops src so it fits in dst. func Thumbnail(dst draw.Image, src image.Image) error { // Scale down src in the dimension that is closer to dst. sb := src.Bounds() db := dst.Bounds() rx := float64(sb.Dx()) / float64(db.Dx()) ry := float64(sb.Dy()) / float64(db.Dy()) var b image.Rectangle if rx < ry { b = image.Rect(0, 0, db.Dx(), int(float64(sb.Dy())/rx)) } else { b = image.Rect(0, 0, int(float64(sb.Dx())/ry), db.Dy()) } buf := image.NewRGBA(b) if err := Scale(buf, src); err != nil { return err } // Crop. // TODO(crawshaw): improve on center-alignment. var pt image.Point if rx < ry { pt.Y = (b.Dy() - db.Dy()) / 2 } else { pt.X = (b.Dx() - db.Dx()) / 2 } draw.Draw(dst, db, buf, pt, draw.Src) return nil }
func main() { rand.Seed(time.Now().UTC().UnixNano()) var templatePath string if len(os.Args) == 1 { templatePath = "tux.png" } else { templatePath = os.Args[1] } template, err := readTemplate(templatePath) if err != nil { panic(err) } templateBounds := template.Bounds() sourceHeight := templateBounds.Max.Y sourceWidth := templateBounds.Max.X cypherHeight := sourceHeight * 2 cypherWidth := sourceWidth * 2 image1 := image.NewRGBA(image.Rect(0, 0, cypherWidth, cypherHeight)) image2 := image.NewRGBA(image.Rect(0, 0, cypherWidth, cypherHeight)) for x := 0; x <= sourceWidth; x++ { for y := 0; y <= sourceHeight; y++ { setPixel(x, y, template.At(x, y), image1, image2) } } writeCypers(image1, image2) }
// cut out the image and return individual channels with image.Image // no encoding of JPEG func cut(original image.Image, db *map[string][3]float64, tileSize, x1, y1, x2, y2 int) <-chan image.Image { c := make(chan image.Image) sp := image.Point{0, 0} go func() { newimage := image.NewNRGBA(image.Rect(x1, y1, x2, y2)) for y := y1; y < y2; y = y + tileSize { for x := x1; x < x2; x = x + tileSize { r, g, b, _ := original.At(x, y).RGBA() color := [3]float64{float64(r), float64(g), float64(b)} nearest := nearest(color, db) file, err := os.Open(nearest) if err == nil { img, _, err := image.Decode(file) if err == nil { t := resize(img, tileSize) tile := t.SubImage(t.Bounds()) tileBounds := image.Rect(x, y, x+tileSize, y+tileSize) draw.Draw(newimage, tileBounds, tile, sp, draw.Src) } else { fmt.Println("error in decoding nearest", err, nearest) } } else { fmt.Println("error opening file when creating mosaic:", nearest) } file.Close() } } c <- newimage.SubImage(newimage.Rect) }() return c }
func (this *Signer) GetMoreLineImage(text string, text_color image.Image, l int, fix_top, fix_bottom int) (image.Image, error) { r := image.Rect(0, 0, 414, 96) img := image.NewNRGBA(r) c := freetype.NewContext() c.SetDPI(this.Dpi) c.SetFont(this.font) c.SetFontSize(this.FontSize) c.SetClip(img.Bounds()) c.SetDst(img) c.SetSrc(text_color) //pt := freetype.Pt(0, 0) pt := freetype.Pt(0, 0+int(c.PointToFix32(this.FontSize)>>8)) var err error limit := c.PixToFix32(l) str := strings.Split(text, "\r\n") for i, s := range str { pt, err = c.DrawString(s, pt, limit) if err != nil { fmt.Println("c.DrawString(%s) error(%v)", s, err) return nil, err } if i < len(str)-1 { pt.Y += c.PointToFix32(this.FontSize * 1.5) } } x, y := l, c.Fix32ToPix(pt.Y) sub_r := image.Rect(0, 0, x+20, y+(fix_bottom-fix_top)) sub_img := image.NewNRGBA(sub_r) draw.Draw(sub_img, sub_r, img, image.Point{0, fix_top}, draw.Src) return sub_img, nil }
// 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 }
// NewImage creates an Image of the given size. // // Both a host-memory *image.RGBA and a GL texture are created. func NewImage(w, h int) *Image { dx := roundToPower2(w) dy := roundToPower2(h) // TODO(crawshaw): Using VertexAttribPointer we can pass texture // data with a stride, which would let us use the exact number of // pixels on the host instead of the rounded up power 2 size. m := image.NewRGBA(image.Rect(0, 0, dx, dy)) glimage.Do(glInit) img := &Image{ RGBA: m.SubImage(image.Rect(0, 0, w, h)).(*image.RGBA), Texture: gl.GenTexture(), texWidth: dx, texHeight: dy, } // TODO(crawshaw): We don't have the context on a finalizer. Find a way. // runtime.SetFinalizer(img, func(img *Image) { gl.DeleteTexture(img.Texture) }) gl.BindTexture(gl.TEXTURE_2D, img.Texture) gl.TexImage2D(gl.TEXTURE_2D, 0, dx, dy, gl.RGBA, gl.UNSIGNED_BYTE, nil) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) return img }
func Crop(m image.Image, r image.Rectangle, w, h int) image.Image { if w < 0 || h < 0 { return nil } if w == 0 || h == 0 || r.Dx() <= 0 || r.Dy() <= 0 { return image.NewRGBA64(image.Rect(0, 0, w, h)) } curw, curh := r.Min.X, r.Min.Y img := image.NewRGBA(image.Rect(0, 0, w, h)) for y := 0; y < h; y++ { for x := 0; x < w; x++ { // Get a source pixel. subx := curw + x suby := curh + y r32, g32, b32, a32 := m.At(subx, suby).RGBA() r := uint8(r32 >> 8) g := uint8(g32 >> 8) b := uint8(b32 >> 8) a := uint8(a32 >> 8) img.SetRGBA(x, y, color.RGBA{r, g, b, a}) } } return img }
func BenchmarkEncode(b *testing.B) { b.StopTimer() bo := image.Rect(0, 0, 640, 480) rnd := rand.New(rand.NewSource(123)) // Restrict to a 256-color paletted image to avoid quantization path. palette := make(color.Palette, 256) for i := range palette { palette[i] = color.RGBA{ uint8(rnd.Intn(256)), uint8(rnd.Intn(256)), uint8(rnd.Intn(256)), 255, } } img := image.NewPaletted(image.Rect(0, 0, 640, 480), palette) for y := bo.Min.Y; y < bo.Max.Y; y++ { for x := bo.Min.X; x < bo.Max.X; x++ { img.Set(x, y, palette[rnd.Intn(256)]) } } b.SetBytes(640 * 480 * 4) b.StartTimer() for i := 0; i < b.N; i++ { Encode(ioutil.Discard, img, nil) } }
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) }