//水印 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() }
func Fuzz(data []byte) int { cfg, err := png.DecodeConfig(bytes.NewReader(data)) if err != nil { return 0 } if cfg.Width*cfg.Height > 1e6 { return 0 } img, err := png.Decode(bytes.NewReader(data)) if err != nil { return 0 } for _, c := range []png.CompressionLevel{png.DefaultCompression, png.NoCompression, png.BestSpeed, png.BestCompression} { var w bytes.Buffer e := &png.Encoder{c} err = e.Encode(&w, img) if err != nil { panic(err) } img1, err := png.Decode(&w) if err != nil { panic(err) } if !reflect.DeepEqual(img.Bounds(), img1.Bounds()) { fmt.Printf("bounds0: %#v\n", img.Bounds()) fmt.Printf("bounds1: %#v\n", img1.Bounds()) panic("bounds have changed") } } return 1 }
func main() { f, err := os.Open(os.Args[1]) if err != nil { fmt.Println(err) return } defer f.Close() i50, err := png.Decode(f) if err != nil { fmt.Println(err) return } if f, err = os.Open(os.Args[2]); err != nil { fmt.Println(err) return } defer f.Close() i100, err := png.Decode(f) if err != nil { fmt.Println(err) return } if i50.ColorModel() != i100.ColorModel() { fmt.Println("different color models") return } b := i50.Bounds() if !b.Eq(i100.Bounds()) { fmt.Println("different image sizes") return } var sum int64 for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { r1, g1, b1, _ := i50.At(x, y).RGBA() r2, g2, b2, _ := i100.At(x, y).RGBA() if r1 > r2 { sum += int64(r1 - r2) } else { sum += int64(r2 - r1) } if g1 > g2 { sum += int64(g1 - g2) } else { sum += int64(g2 - g1) } if b1 > b2 { sum += int64(b1 - b2) } else { sum += int64(b2 - b1) } } } nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y) fmt.Printf("Image difference: %f%%\n", float64(sum*100)/(float64(nPixels)*0xffff*3)) }
func init() { var err error Terrain, err = png.Decode(bytes.NewReader(TerrainPng)) if err != nil { panic(err) } TerrainPng = nil Actors, err = png.Decode(bytes.NewReader(ActorsPng)) if err != nil { panic(err) } ActorsPng = nil }
func fixtureImageObj(fpath string) image.Image { f, _ := os.Open(fpath) buf, _ := ioutil.ReadFile(f.Name()) img, _ := png.Decode(bytes.NewReader(buf)) // *image.RGBA return img }
//func loadSize(ctxt *fs.Context, name string, max int) *image.RGBA func loadSize(name string, max int) *image.RGBA { //data, _, err := ctxt.Read("qr/upload/" + name + ".png") f1, err := os.Open(name + ".png") fmt.Println(name + ".png") if err != nil { panic(err) } i, err := png.Decode(f1) if err != nil { panic(err) } b := i.Bounds() fmt.Printf("%v, %v,max%v", b.Dx(), b.Dy(), max) dx, dy := max, max if b.Dx() > b.Dy() { dy = b.Dy() * dx / b.Dx() } else { dx = b.Dx() * dy / b.Dy() } fmt.Printf("%v, %v,", dx, dy) var irgba *image.RGBA switch i := i.(type) { case *image.RGBA: irgba = resize.ResizeRGBA(i, i.Bounds(), dx, dy) case *image.NRGBA: irgba = resize.ResizeNRGBA(i, i.Bounds(), dx, dy) default: fmt.Println("default") } fmt.Println("prereturnload") fmt.Printf("%v, %v,", irgba.Bounds().Dx(), irgba.Bounds().Dy()) return irgba }
func main() { if len(os.Args) != 2 { fmt.Println("Please select one picture to makeascii...") return } fileName := os.Args[1] isJpeg, _ := regexp.MatchString(".+\\.jpg", fileName) isPng, _ := regexp.MatchString(".+\\.png", fileName) var picture image.Image var imageErr error fileIn, errIn := os.Open(fileName) if errIn != nil { fmt.Println(errIn.Error()) return } if isJpeg { picture, imageErr = jpeg.Decode(fileIn) } else if isPng { picture, imageErr = png.Decode(fileIn) } else { fmt.Println("File type is not supported...") return } if imageErr != nil { fmt.Println(imageErr.Error()) return } fmt.Print(MakeAscii(GetImage(picture))) }
func createTexture(r io.Reader) (textureId gl.Uint, err error) { img, err := png.Decode(r) if err != nil { return 0, err } rgbaImg, ok := img.(*image.NRGBA) if !ok { return 0, errors.New("texture must be an NRGBA image") } gl.GenTextures(1, &textureId) gl.BindTexture(gl.TEXTURE_2D, textureId) gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) gl.TexParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) // flip image: first pixel is lower left corner imgWidth, imgHeight := img.Bounds().Dx(), img.Bounds().Dy() data := make([]byte, imgWidth*imgHeight*4) lineLen := imgWidth * 4 dest := len(data) - lineLen for src := 0; src < len(rgbaImg.Pix); src += rgbaImg.Stride { copy(data[dest:dest+lineLen], rgbaImg.Pix[src:src+rgbaImg.Stride]) dest -= lineLen } gl.TexImage2D(gl.TEXTURE_2D, 0, 4, gl.Sizei(imgWidth), gl.Sizei(imgHeight), 0, gl.RGBA, gl.UNSIGNED_BYTE, gl.Pointer(&data[0])) return textureId, nil }
func TestDescriptor(t *testing.T) { square, err := os.Open("../test/images/square.png") if err != nil { t.Fatal(err) } img, err := png.Decode(square) points := make(chan image.Point, 2) go func() { points <- image.Point{16, 16} close(points) }() desc := make(chan Descriptor) CalcDescriptors(points, img, desc, RGBPointValue) i := 0 for d := range desc { if d.base != 16191 { t.Logf("Base value of descriptor should be 15, instead it was %v", d.base) t.Fail() } i++ } if i != 1 { t.Logf("CalcDescriptor should have returned exactly 1 descriptor, given 1 point") t.Fail() } }
func readTarget(name string) ([][]int, error) { f, err := os.Open(name) if err != nil { return nil, err } m, err := png.Decode(f) if err != nil { return nil, fmt.Errorf("decode %s: %v", name, err) } rect := m.Bounds() target := make([][]int, rect.Dy()) for i := range target { target[i] = make([]int, rect.Dx()) } for y, row := range target { for x := range row { a := int(color.RGBAModel.Convert(m.At(x, y)).(color.RGBA).A) t := int(color.GrayModel.Convert(m.At(x, y)).(color.Gray).Y) if a == 0 { t = -1 } row[x] = t } } return target, nil }
func main() { var file *os.File var outFile *os.File var img image.Image var err error if file, err = os.Open("pkg.png"); err != nil { println("Error", err) return } defer file.Close() if img, err = png.Decode(file); err != nil { println("Error", err) return } if outFile, err = os.Create("out_pkg.jpeg"); err != nil { println("Error", err) return } option := &jpeg.Options{Quality: 100} if err = jpeg.Encode(outFile, img, option); err != nil { println() return } defer outFile.Close() }
func CountColor(_png io.Reader) int { /* modify here */ config, err := png.DecodeConfig(_png) if err != nil { log.Fatal(err) } width := config.Width * 10 height := config.Height * 10 _png = GetPngBinary() img, err := png.Decode(_png) if err != nil { log.Fatal(err) } var r, g, b, a uint32 var str string m := make(map[string]int) for x := 0; x < width; x++ { for y := 0; y < height; y++ { r, g, b, a = img.At(x, y).RGBA() str = strconv.Itoa(int(r)) + strconv.Itoa(int(g)) + strconv.Itoa(int(b)) + strconv.Itoa(int(a)) m[str] = 1 } } return len(m - 1) }
func convertPNGToJPEG(w io.Writer, r io.Reader, quality int) error { img, err := png.Decode(r) if err != nil { return err } return jpeg.Encode(w, img, &jpeg.Options{Quality: quality}) }
func main() { flag.Parse() if len(flag.Args()) != 1 { fmt.Println("Usage: goicns -o IconSet.icns image.png") return } path := flag.Args()[0] f, err := os.OpenFile(path, os.O_RDONLY, 0600) if err != nil { fmt.Println("Error opening image %s: %s", path, err.Error()) return } img, err := png.Decode(f) if err != nil { fmt.Println("Error decoding image %s: %s", path, err.Error()) return } icns := goicns.NewICNS(img) if err = icns.Construct(); err != nil { fmt.Println("Error encofing ICNS %s: %s", path, err.Error()) return } icns.WriteToFile(*flOut, 0666) }
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() }
func run() error { qml.Init(nil) engine := qml.NewEngine() engine.AddImageProvider("pwd", func(id string, width, height int) image.Image { f, err := os.Open(id) if err != nil { panic(err) } defer f.Close() image, err := png.Decode(f) if err != nil { panic(err) } return image }) component, err := engine.LoadFile("imgprovider.qml") if err != nil { return err } win := component.CreateWindow(nil) win.Show() win.Wait() return nil }
func (vr *VaultRenderer) LoadTexture(name string) *splish.Sprite { if tex, ok := textures[name]; ok { return tex } // get an asset path imgName := name if !strings.HasSuffix(imgName, ".png") { imgName += ".png" } parts := strings.Split("assets/"+imgName, "/") path := filepath.Join(parts...) f, err := os.Open(path) if err != nil { log.Println("Couldn't open file:", path, err) return textures["blank"] } // decode png, convert to RGBA img, err := png.Decode(f) if err != nil { log.Println("Couldn't decode file:", err) return textures["blank"] } rgba := image.NewRGBA(img.Bounds()) draw.Draw(rgba, rgba.Bounds(), img, image.ZP, draw.Src) // Push it out to the window to get uploaded tex := vr.Scene.NewSprite(rgba) textures[name] = tex return tex }
func TestNewRevisitImageWithPNG(t *testing.T) { pngMsg, err := NewRevisitMsgFromFiles("./fixtures/connie.png") if err != nil { t.Fatal(err) } ri, err := NewRevisitImageFromMsg(pngMsg) if err != nil { t.Fatal(err) } if len(ri.Rgbas) != 1 { t.Errorf("ri.Rgbas length should be 1, is %d", len(ri.Rgbas)) } if len(ri.Delay) != 1 { t.Errorf("ri.Delay length should be 1, is %d", len(ri.Delay)) } if ri.LoopCount != 0 { t.Errorf("LoopCount should be 0, is %d", ri.LoopCount) } ri.Transform(mockTransform) m, err := ri.RevisitMsg() if err != nil { t.Error(err) } _, err = png.Decode(m.ImageByteReader()) if err != nil { t.Error(err) } }
func (s *Screening) createGIF(force bool) error { fn := s.GIFPath() if !force { if _, err := os.Stat(fn); err == nil { return nil } } outGIF := &gif.GIF{} for i := uint(0); i < s.Steps; i++ { f, err := os.Open(s.ScreenshotPath(i)) if err != nil { return err } defer f.Close() img, err := png.Decode(f) if err != nil { return err } paletted := image2paletted(720, img) outGIF.Image = append(outGIF.Image, paletted) outGIF.Delay = append(outGIF.Delay, 100) } f, err := os.Create(fn) if err != nil { return err } defer f.Close() return gif.EncodeAll(f, outGIF) }
func readImagePng(filename string) (image []Spectrum, width, height int) { f, err := os.Open(filename) defer f.Close() if err != nil { Error("Error reading PNG \"%s\"", filename) return nil, 0, 0 } pngImage, err := png.Decode(f) if err != nil { Error("Error decoding PNG \"%s\"", filename) return nil, 0, 0 } bounds := pngImage.Bounds() width = bounds.Dx() height = bounds.Dy() image = make([]Spectrum, width*height, width*height) for y := 0; y < height; y++ { for x := 0; x < width; x++ { rb, gb, bb, _ := pngImage.At(x, y).RGBA() r := float64(rb) / float64(0xffff) g := float64(gb) / float64(0xffff) b := float64(bb) / float64(0xffff) image[y*width+x] = *NewSpectrumRGB(r, g, b) } } return image, width, height }
func loadImage() ([]byte, int, int) { // Open the file. file, err := os.Open("gopher.png") if err != nil { log.Fatal(err) } defer file.Close() // Decode the image. img, err := png.Decode(file) if err != nil { log.Fatal(err) } bounds := img.Bounds() width, height := bounds.Size().X, bounds.Size().Y buffer := make([]byte, width*height*4) index := 0 for y := bounds.Min.Y; y < bounds.Max.Y; y++ { for x := bounds.Min.X; x < bounds.Max.X; x++ { r, g, b, a := img.At(x, y).RGBA() buffer[index] = byte(r) buffer[index+1] = byte(g) buffer[index+2] = byte(b) buffer[index+3] = byte(a) index += 4 } } return buffer, width, height }
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) } }
func readImage(data []byte, format string) (image.Image, error) { reader := bytes.NewReader(data) if format == "png" { return png.Decode(reader) } return jpeg.Decode(reader) }
// Using biom borders to generate slow but random-tolerance tile hash func generateBorderHash(imagePath string) []byte { var invalidHash []byte = nil file, err := os.Open(imagePath) if err != nil { fmt.Printf("Cannot generate image hash #1\n") return invalidHash } defer file.Close() tileImage, err := png.Decode(file) if err != nil { fmt.Printf("Cannot generate image '%s' hash #2: %s\n", imagePath, err.Error()) return invalidHash } bounds := tileImage.Bounds() h := md5.New() blackCount := 0 pixelsCount := 0 // some tiles contain artifacts near the borders for x := 5; x < bounds.Max.X-5; x++ { for y := 5; y < bounds.Max.Y-5; y++ { pixel := tileImage.At(x, y) r, g, b, _ := pixel.RGBA() if r == 0 && g == 0 && b == 0 { binary.Write(h, binary.LittleEndian, []byte(strconv.Itoa(x))) binary.Write(h, binary.LittleEndian, []byte(strconv.Itoa(y))) blackCount++ } pixelsCount++ } } if blackCount == 0 || blackCount == pixelsCount { return invalidHash } return h.Sum(nil) }
func loadLogos(context appengine.Context, globpaths ...string) map[string][]image.Image { logoImagesByName := make(map[string][]image.Image) for _, path := range globpaths { logoFolders, err := filepath.Glob(path + "/*") check(err, context) for _, logoFolder := range logoFolders { logoFiles, err := filepath.Glob(logoFolder + "/*") check(err, context) filename := filepath.Base(logoFolder) logoImages := make([]image.Image, 0) for _, logoFile := range logoFiles { //fmt.Fprintf(os.Stderr, "%s\n", logoFile) logoData, err := os.Open(logoFile) defer logoData.Close() check(err, context) reader := bufio.NewReader(logoData) logoImage, err := png.Decode(reader) check(err, context) logoImages = append(logoImages, logoImage) } logoImagesByName[filename] = logoImages } } return logoImagesByName }
func loader(inChan chan loaderRequest, outChan chan *Image, errChan chan *Error, stopChan chan int) { for { select { case req := <-inChan: switch strings.ToLower(path.Ext(req.name)) { case ".jpg": if img, err := jpeg.Decode(req.reader); err == nil { outChan <- &Image{Name: req.name, Data: img} } else { errChan <- &Error{Name: req.name, Message: err.Error()} } case ".png": if img, err := png.Decode(req.reader); err == nil { outChan <- &Image{Name: req.name, Data: img} } else { errChan <- &Error{Name: req.name, Message: err.Error()} } } if err := req.reader.Close(); err != nil { fmt.Errorf("%s\n", err) } case <-stopChan: return } } }
// TestMean tests the mean quantizer on png files found in the source // directory. Output files are prefixed with _mean_. Files begining with // _ are skipped when scanning for input files. Note nothing is tested // with a fresh source tree--drop a png or two in the source directory // before testing to give the test something to work on. Png files in the // parent directory are similarly used for testing. Put files there // to compare results of the different quantizers. func TestMean(t *testing.T) { for _, p := range glob(t) { f, err := os.Open(p) if err != nil { t.Log(err) // skip files that can't be opened continue } img, err := png.Decode(f) f.Close() if err != nil { t.Log(err) // skip files that can't be decoded continue } pDir, pFile := filepath.Split(p) for _, n := range []int{16, 256} { // prefix _ on file name marks this as a result fq, err := os.Create(fmt.Sprintf("%s_mean_%d_%s", pDir, n, pFile)) if err != nil { t.Fatal(err) // probably can't create any others } var q quant.Quantizer = mean.Quantizer(n) if err = png.Encode(fq, q.Image(img)); err != nil { t.Fatal(err) // any problem is probably a problem for all } } } }
func OpenBAMD(r io.ReadSeeker, palettePath string) (*BAM, error) { var d decoder if err := d.decode_bamd(r); err != nil { return nil, err } bam := &BAM{ Image: d.image, Sequences: d.sequences, SequenceToImage: d.FrameLUT, Width: d.width, Height: d.height, Frames: d.Frames, Palette: d.colorMap, } bam.RebuildSequencesAndDropFrames() if _, err := os.Stat(palettePath); err == nil { log.Printf("Using palette at: %s\n", palettePath) paletteFile, err := os.Open(palettePath) if err != nil { return nil, fmt.Errorf("Unable to open palette %s: %v", palettePath, err) } defer paletteFile.Close() palette_template_img, err := png.Decode(paletteFile) if err != nil { return nil, fmt.Errorf("Unable to decode png %s: %v", palettePath, err) } bam.Palette = palette_template_img.ColorModel().(color.Palette) } return bam, nil }
// default image format: jpeg func (this *Avatar) Encode(wr io.Writer, size int) (err error) { var img image.Image decodeImageFile := func(file string) (img image.Image, err error) { fd, err := os.Open(file) if err != nil { return } defer fd.Close() if img, err = jpeg.Decode(fd); err != nil { fd.Seek(0, os.SEEK_SET) img, err = png.Decode(fd) } return } imgPath := this.imagePath if !this.HasCache() { if this.AlterImage == "" { return errors.New("request image failed, and no alt image offered") } imgPath = this.AlterImage } if img, err = decodeImageFile(imgPath); err != nil { return } m := resize.Resize(uint(size), 0, img, resize.NearestNeighbor) return jpeg.Encode(wr, m, nil) }
func thumb() image.Image { imageName := "test.jpg" imageFile, err := os.Open(imageName) if err != nil { log.Fatal(err) } var myImage *image.Image switch strings.ToLower(path.Ext(imageName)) { case ".jpg", ".jpeg": img, err := jpeg.Decode(imageFile) if err != nil { log.Fatal(err) } myImage = &img case ".png": img, err := png.Decode(imageFile) if err != nil { log.Fatal(err) } myImage = &img } imageFile.Close() m := resize.Resize(0, 200, *myImage, resize.MitchellNetravali) return m }