Пример #1
0
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)
}
Пример #2
0
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
}
Пример #3
0
func DecodeConfig(r io.Reader) (image.Config, error) {
	var (
		d   decoder
		cfg image.Config
		err error
	)
	if err = d.decodeHeader(r); err != nil {
		return cfg, err
	}
	if err = d.decodeEntries(r); err != nil {
		return cfg, err
	}
	e := d.entries[0]
	buf := make([]byte, e.Size+14)
	n, err := io.ReadFull(r, buf[14:])
	if err != nil && err != io.ErrUnexpectedEOF {
		return cfg, err
	}
	buf = buf[:14+n]
	if n > 8 && bytes.Compare(buf[14:22], pngHeader) == 0 {
		return png.DecodeConfig(bytes.NewReader(buf[14:]))
	}

	d.forgeBMPHead(buf, &e)
	return bmp.DecodeConfig(bytes.NewReader(buf))
}
Пример #4
0
func parsePNG(r io.Reader) (int, int, error) {
	cfg, err := png.DecodeConfig(r)
	if err != nil {
		return 0, 0, err
	}

	return cfg.Width, cfg.Height, nil
}
Пример #5
0
func (s *testService) assertSprite(path string, width, height int) {
	buf := s.sprites[path]
	Ω(buf).ShouldNot(BeNil())
	config, err := png.DecodeConfig(bytes.NewReader(buf.Bytes()))
	Ω(err).Should(Succeed())
	Ω(config.Width).Should(Equal(width))
	Ω(config.Height).Should(Equal(height))
}
Пример #6
0
func PngDecodeConfigFromFile(path string) (conf image.Config, err error) {
	file, err := os.Open(path)
	if err != nil {
		return
	}
	defer file.Close()
	return png.DecodeConfig(file)
}
Пример #7
0
func main() {

	width := 1200.0
	height := 200.0

	flag.Parse()
	canvas.Start(width, height)
	canvas.Title("Planets")
	canvas.Rect(0, 0, width, height, "fill:black")
	nobj := len(ssDist)
	y := height / 2.0
	margin := 100.0
	minsize := 7.0
	labeloc := height / 4.0

	var x, r, imScale, maxh float64
	var px, po float64

	if *showdisk {
		maxh = float64(height) / minsize
	} else {
		maxh = float64(height) / 4.0
	}
	for i := 1; i < int(nobj); i++ {
		x = vmap(ssDist[i], ssDist[1.0], ssDist[nobj-1.0], float64(margin), float64(width-margin))
		r = (vmap(ssRad[i], ssRad[1.0], ssRad[nobj-1.0], minsize, maxh)) / 2.0
		px = float64(x)
		if *showdisk {
			po = 0.0
			canvas.Circle(px, y, float64(r), "fill:#"+ssColor[i])
		} else { // show images
			f, err := os.Open(ssImages[i])
			if err != nil {
				println("bad image file:", ssImages[i])
				continue
			}
			defer f.Close()
			p, perr := png.DecodeConfig(f)
			if perr != nil {
				println("bad decode:", ssImages[i])
				continue
			}
			imScale = r / float64(p.Width)
			hs := float64(p.Height) * imScale
			dy := y - (float64(hs) / 2.0) // center the image
			po = float64(r) / 2.0
			canvas.Image(px, dy, float64(r), float64(hs), ssImages[i])
		}
		if ssDist[i] == 1.0 { // earth
			canvas.Line(px+po, y-po, px+po, y-labeloc,
				"stroke-width:1px;stroke:white")
			canvas.Text(px+po, y-labeloc-10, "You are here",
				"fill:white; font-size:14px; font-family:Calibri; text-anchor:middle")
		}
	}
	canvas.End()
}
Пример #8
0
func main() {
	flag.Parse()
	width, height := *cw, *ch
	tfmt := "fill:white; font-size:%dpx; font-family:Calibri,sans; text-anchor:middle"
	canvas.Start(width, height)
	canvas.Title("Planets")
	canvas.Rect(0, 0, width, height, "fill:black")
	nobj := len(ssDist)
	y := height / 2
	margin := 100
	minsize := 7.0
	labeloc := height / 4
	fontsize := (width * 20) / 1000

	var x, r, imScale, maxh float64
	var px, po int

	if *showdisk {
		maxh = float64(height) / minsize
	} else {
		maxh = float64(height) / 4.0
	}
	for i := 1; i < nobj; i++ {
		x = vmap(ssDist[i], ssDist[1], ssDist[nobj-1], float64(margin), float64(width-margin))
		r = (vmap(ssRad[i], ssRad[1], ssRad[nobj-1], minsize, maxh)) / 2
		px = int(x)
		if *showdisk {
			po = 0
			canvas.Circle(px, y, int(r), "fill:#"+ssColor[i])
		} else { // show images
			f, err := os.Open(ssImages[i])
			if err != nil {
				fmt.Fprintf(os.Stderr, "%s: %s\n", err, ssImages[i])
				continue
			}
			defer f.Close()
			p, perr := png.DecodeConfig(f)
			if perr != nil {
				fmt.Fprintf(os.Stderr, "%s: %s\n", perr, ssImages[i])
				continue
			}
			imScale = r / float64(p.Width)
			hs := float64(p.Height) * imScale
			dy := y - (int(hs) / 2) // center the image
			po = int(r) / 2
			canvas.Image(px, dy, int(r), int(hs), ssImages[i])
		}
		if ssDist[i] == 1.0 && *showyou { // earth
			canvas.Line(px+po, y-po, px+po, y-labeloc,
				"stroke-width:1px;stroke:white")
			canvas.Text(px+po, y-labeloc-10, "You are here", fmt.Sprintf(tfmt, fontsize))
		}
	}
	canvas.End()
}
Пример #9
0
func main() {

	width := 1300
	height := 200

	flag.Parse()
	canvas.Start(width, height)
	canvas.Title("Planets")
	canvas.Rect(0, 0, width, height, "fill:black")
	canvas.Gstyle("stroke:none")
	nobj := len(ssDist)
	y := height / 2
	margin := 100
	minsize := 7.0
	labeloc := height / 4

	var x, r, imScale, maxh float64

	if *showimages {
		maxh = float64(height) / 4.0
	} else {
		maxh = float64(height) / minsize
	}

	for i := 1; i < nobj; i++ {
		x = vmap(ssDist[i], ssDist[1], ssDist[nobj-1], float64(margin), float64(width-margin))
		r = (vmap(ssRad[i], ssRad[1], ssRad[nobj-1], minsize, maxh)) / 2
		if *showimages {
			f, err := os.Open(ssImages[i])
			defer f.Close()
			if err != nil {
				continue
			}
			p, perr := png.DecodeConfig(f)
			if perr != nil {
				continue
			}
			imScale = r / float64(p.Width)
			hs := float64(p.Height) * imScale
			dy := y - (int(hs) / 2) // center the image
			canvas.Image(int(x), dy, int(r), int(hs), ssImages[i])
		} else {
			canvas.Circle(int(x), int(y), int(r), "fill:#"+ssColor[i])
		}
		if ssDist[i] == 1.0 { // earth
			canvas.Line(int(x), int(y), int(x), int(y)-labeloc, "stroke:white")
			canvas.Text(int(x), int(y)-labeloc-10, "You are here", "fill:white; font-size:14; font-family:Calibri; text-anchor:middle")
		}
	}
	canvas.Gend()
	canvas.End()
}
Пример #10
0
func getImageDimension(imagePath string) (int, int) {
	file, err := os.Open(imagePath)
	if err != nil {
		fmt.Printf("Cannot get image size #1\n")
		return 0, 0
	}
	defer file.Close()
	image, err := png.DecodeConfig(file)
	if err != nil {
		fmt.Printf("Cannot get image size #2: %s\n", err.Error())
		return 0, 0
	}
	return image.Width, image.Height
}
Пример #11
0
func validPNGFile(fn string) bool {
	pngImage, err := os.Open(fn)

	check(err)

	defer pngImage.Close()

	_, err = png.DecodeConfig(pngImage)

	if err != nil {
		return false
	}

	return true
}
Пример #12
0
func decodePNG(f multipart.File) (*Image, error) {
	var image Image

	ic, err := png.DecodeConfig(f)
	_, err = f.Seek(0, 0)
	i, err := png.Decode(f)

	if err != nil {
		return nil, fmt.Errorf("Could not decode PNG file.")
	}

	image.Config = ic
	image.Image = i

	return &image, nil
}
Пример #13
0
func Example_body() {
	cmd := exec.Command("./cdc", "body", "-addr", "2684420101", "../../testcache")

	output := new(bytes.Buffer)
	cmd.Stdout = output

	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}

	config, err := png.DecodeConfig(output)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("PNG image data, %d x %d\n", config.Width, config.Height)
	// Output:
	// PNG image data, 83 x 120
}
Пример #14
0
func visit(path string, f os.FileInfo, err error) error {
	i, ierr := os.Open(path)
	defer i.Close()
	if ierr != nil {
		return err
	}

	// check if file jpg or png
	// get dimensions of images
	// lowres images to other directory and highres to another

	switch strings.ToLower(filepath.Ext(path)) {

	case ".jpg", ".jpeg":
		j, jerr := jpeg.DecodeConfig(i)
		i.Close()
		if jerr != nil {
			return jerr
		}
		v, fname := validateResolution(j), f.Name()
		err := move(path, fname, v)
		if err != nil {
			fmt.Println(err)
		}
		return nil

	case ".png":
		p, perr := png.DecodeConfig(i)
		i.Close()
		if perr != nil {
			return perr
		}
		v, fname := validateResolution(p), f.Name()
		err := move(path, fname, v)
		if err != nil {
			fmt.Println(err)
		}
		return nil
	}

	return nil
}
Пример #15
0
// Example gets an entry from the cache and prints to stdout.
func Example() {
	cache, err := cdc.OpenCache("testcache")
	if err != nil {
		log.Fatal(err)
	}

	entry, err := cache.OpenURL("https://golang.org/doc/gopher/pkg.png")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(entry.URL())

	header, err := entry.Header()
	if err != nil {
		log.Fatal(err)
	}
	for _, key := range []string{"Status", "Content-Length", "Content-Type"} {
		fmt.Printf("%s: %s\n", key, header.Get(key))
	}

	body, err := entry.Body()
	if err != nil {
		log.Fatal(err)
	}
	defer body.Close()

	config, err := png.DecodeConfig(body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("PNG image data, %d x %d\n", config.Width, config.Height)

	// Output:
	// https://golang.org/doc/gopher/pkg.png
	// Status: 200
	// Content-Length: 5409
	// Content-Type: image/png
	// PNG image data, 83 x 120
}
Пример #16
0
func (this *UploadedFile) Dimensions() (int, int, error) {
	f, err := os.Open(this.path)
	if err != nil {
		return 0, 0, err
	}

	var cfg image.Config
	switch true {
	case this.IsGif():
		cfg, err = gif.DecodeConfig(f)
	case this.IsPng():
		cfg, err = png.DecodeConfig(f)
	case this.IsJpeg():
		cfg, err = jpeg.DecodeConfig(f)
	default:
		return 0, 0, errors.New("Invalid mime type!")
	}

	if err != nil {
		return 0, 0, err
	}

	return cfg.Width, cfg.Height, nil
}
Пример #17
0
func _decode_album(src string) (Album, Album) {
	photoList, _ := filepath.Glob(src + "\\*")
	var album Album
	var albumSummary Album
	var imgInfo image.Config
	var comment_str string
	decoder := mahonia.NewDecoder("UTF-16LE")

	for key := range photoList {
		fullFileName := photoList[key]

		//读取图片长宽等信息
		photo_fi, err := os.Open(fullFileName)
		if err != nil {
			log.Fatal(err)
		}
		defer photo_fi.Close()
		switch strings.ToLower(path.Ext(fullFileName)) {
		case ".jpg", ".jpeg":
			imgInfo, err = jpeg.DecodeConfig(photo_fi)
			if err != nil {
				fmt.Println("图片解析错误:" + fullFileName)
				os.Exit(0)
			}

		case ".png":
			imgInfo, err = png.DecodeConfig(photo_fi)
			if err != nil {
				fmt.Println("图片解析错误:" + fullFileName)
				os.Exit(0)
			}

		case ".gif":
			imgInfo, err = gif.DecodeConfig(photo_fi)
			if err != nil {
				fmt.Println("图片解析错误:" + fullFileName)
				os.Exit(0)
			}
		default:
			continue
		}

		//读取图片评注信息
		photo_fi, err = os.Open(fullFileName)
		if err != nil {
			log.Fatal(err)
		}
		photo_exif, err := exif.Decode(photo_fi)
		if err != nil {
			comment_str = ""
		} else {
			comment, err := photo_exif.Get(exif.UserComment)
			if err != nil {
				comment_str = ""
			} else {
				comment_str = decoder.CConvertString(comment.Val)
			}
		}
		photo_fi.Close()

		var bigPhotoFileName, photoFileName string
		photoFileName = filepath.Base(fullFileName)
		if strings.ToLower(path.Ext(fullFileName)) == ".gif" || imgInfo.Width < siteInfo.ImgWidth { //global var : SiteInfo
			bigPhotoFileName = photoFileName
		} else {
			bigPhotoFileName = "big_" + photoFileName
		}

		//追加图片信息
		var photo = Photo{Src: fullFileName, Comment: comment_str, Width: imgInfo.Width, Height: imgInfo.Height, PhotoFileName: photoFileName, BigPhotoFileName: bigPhotoFileName}
		album = append(album, photo)
		if strings.HasPrefix(filepath.Base(fullFileName), "~") {
			albumSummary = append(albumSummary, photo)
		}

	}
	return album, albumSummary
}
Пример #18
0
func UploadHandler(conn *rtgo.Conn, data []byte, msg *rtgo.Message) {
	schema := make(map[string]interface{})
	err := json.Unmarshal(msg.Payload, &schema)
	if err != nil {
		log.Println(err)
		return
	}
	topic := schema["topic"].(string)
	now := time.Now()
	schema["timestamp"] = fmt.Sprintf("%d/%d/%d(%s)%d:%d:%d", now.Month(), now.Day(), now.Year(), now.Weekday().String()[:3], now.Hour(), now.Minute(), now.Second())
	schema["uuid"] = uuid.NewV4().String()
	hash := fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%s%s", schema["timestamp"], schema["uuid"]))))[:9]
	schema["hash"] = hash
	if file, ok := schema["file"].(string); ok {
		file_path := fmt.Sprintf("./static/images/uploads/%s", schema["file_name"])
		fdata, err := dataurl.DecodeString(file)
		if err != nil {
			log.Println(err)
			return
		}
		ioutil.WriteFile(file_path, fdata.Data, 0775)
		saved_file, err := os.Open(file_path)
		if err != nil {
			log.Println(err)
			return
		}
		var config image.Config
		if schema["file_mime"] == "image/jpeg" {
			config, err = jpeg.DecodeConfig(saved_file)
		} else if schema["file_mime"] == "image/png" {
			config, err = png.DecodeConfig(saved_file)
		} else if schema["file_mime"] == "image/gif" {
			config, err = gif.DecodeConfig(saved_file)
		}
		schema["file_dimensions"] = fmt.Sprintf("%dx%d", config.Width, config.Height)
		delete(schema, "file")
	}
	if schema["type"] == "thread" {
		if err := app.DB.InsertObj(topic, hash, schema); err != nil {
			return
		}
	} else if schema["type"] == "reply" {
		thread := schema["thread"].(string)
		if obj, err := app.DB.GetObj(topic, thread); err == nil {
			thisobj := obj.(map[string]interface{})
			replies := thisobj["replies"].(map[string]interface{})
			replies[hash] = schema
			tagging := schema["tagging"].([]interface{})
			for _, tag := range tagging {
				if tag.(string) == thread {
					thisobj["taggedBy"] = append(thisobj["taggedBy"].([]interface{}), hash)
				} else if _, ok := replies[tag.(string)]; ok {
					reply := replies[tag.(string)].(map[string]interface{})
					reply["taggedBy"] = append(reply["taggedBy"].([]interface{}), hash)
				}
			}
			if err := app.DB.InsertObj(topic, thread, thisobj); err != nil {
				log.Println(err)
				return
			}
		} else {
			log.Println(err)
			return
		}
	}
	payload, err := json.Marshal(&schema)
	if err != nil {
		log.Println(err)
		return
	}
	response := &rtgo.Message{
		RoomLength:    len(schema["topic"].(string)),
		Room:          schema["topic"].(string),
		EventLength:   len("new-" + schema["type"].(string)),
		Event:         "new-" + schema["type"].(string),
		DstLength:     0,
		Dst:           "",
		SrcLength:     len(conn.Id),
		Src:           conn.Id,
		PayloadLength: len(payload),
		Payload:       payload,
	}
	binary_response := rtgo.MessageToBytes(response)
	conn.Emit(binary_response, response)
	conn.Send <- binary_response
}