Exemplo n.º 1
0
func (s *ResizeSuite) TestResizeImage(c *C) {
	file, err := ioutil.ReadFile("test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	for width, height := range sizes {
		ctx := &fetch.CacheContext{
			Width: width,
		}

		data := bytes.NewBuffer(file)

		orig, _, err := fetch.GetRotatedImage(data)
		c.Check(err, IsNil)

		buf := new(bytes.Buffer)
		jpeg.Encode(buf, orig, nil)

		resized, err := fetch.Resize(buf, ctx)
		c.Check(err, IsNil)

		image, _, err := image.Decode(resized)
		c.Check(err, IsNil)
		c.Check(image.Bounds().Size().X, Equals, width)
		c.Check(image.Bounds().Size().Y, Equals, height)
	}
}
Exemplo n.º 2
0
func (s *ResizeSuite) TestResizeImageSquare(c *C) {
	file, err := ioutil.ReadFile("test/awesome.jpeg")
	c.Assert(err, IsNil)

	for width, _ := range sizes {
		ctx := &fetch.CacheContext{
			Width: width,
			Crop:  true,
		}

		buf := bytes.NewReader(file)
		resized, err := fetch.Resize(buf, ctx)
		c.Check(err, IsNil)

		image, _, err := image.Decode(resized)
		c.Check(err, IsNil)

		if width > 768 {
			width = 768
		}

		c.Check(image.Bounds().Size().X, Equals, width)
		c.Check(image.Bounds().Size().Y, Equals, width)
	}
}
Exemplo n.º 3
0
func ReadBinary(tbl [][]byte, name string) (r string) {
	image := GetPngData(name)
	gw := image.Bounds().Max.X
	gh := image.Bounds().Max.Y
	for y := 12; y < gh-H; y += 22 {
		for x := 9; x < gw-W; x += 36 {
			s0 := SplitImage(image, W, H, x, y)
			if IsOne(s0) {
				continue
			}
			a := FindNum(tbl, s0)
			s1 := SplitImage(image, W, H, x+12, y)
			b := FindNum(tbl, s1)
			if a < 0 || b < 0 {
				fmt.Println("bad char", name, x, y, len(r))
				fmt.Println("a", a)
				PutPattern(s0, W)
				fmt.Println("b", b)
				PutPattern(s1, W)
				os.Exit(1)
			}
			v := a*16 + b
			r = r + fmt.Sprintf("%02x", v)
		}
	}
	if len(r) != 62 {
		fmt.Println("bad byte", name, len(r))
		fmt.Println(r)
		os.Exit(1)
	}
	return
}
Exemplo n.º 4
0
func (s _Sprite) save(spriteImg image.Image, items []_ImageItem, fullWidth, fullHeight int) error {
	targetFolder := fmt.Sprintf("public/images/%s", s.entry)
	target := path.Join(targetFolder, s.name+".png")
	if file, err := os.Create(target); err != nil {
		return fmt.Errorf("Cannot create sprite file %s, %v", target, err)
	} else {
		defer file.Close()
		if err := png.Encode(file, spriteImg); err != nil {
			return nil
		}
		target = s.addFingerPrint(targetFolder, s.name+".png")
		loggers.Succ("[Sprite][%s] Saved sprite image: %s", s.entry, target)

		// generate the stylus file
		stylus := "assets/stylesheets/sprites"
		if err := os.MkdirAll(stylus, os.ModePerm|os.ModeDir); err != nil {
			return fmt.Errorf("Cannot mkdir %s, %v", stylus, err)
		}
		stylus = fmt.Sprintf("assets/stylesheets/sprites/%s_%s.styl", s.entry, s.name)
		if stylusFile, err := os.Create(stylus); err != nil {
			return fmt.Errorf("Cannot create the stylus file for sprite %s, %v", stylus, err)
		} else {
			defer stylusFile.Close()

			spriteEntry := SpriteEntry{
				Entry:   s.entry,
				Name:    s.name,
				Url:     fmt.Sprintf("%s/images/%s/%s", s.config.UrlPrefix, s.entry, filepath.Base(target)),
				Sprites: make([]SpriteImage, len(items)),
				Width:   fullWidth / s.pixelRatio,
				Height:  fullHeight / s.pixelRatio,
			}
			lastHeight := 0
			for i, image := range items {
				name := image.name
				name = name[:len(name)-len(filepath.Ext(name))]
				width, height := image.Bounds().Dx(), image.Bounds().Dy()
				if width%s.pixelRatio != 0 || height%s.pixelRatio != 0 {
					loggers.Warn("You have images cannot be adjusted by the pixel ratio, %s, bounds=%v, pixelRatio=%d",
						image.fullpath, image.Bounds(), s.pixelRatio)
				}
				spriteEntry.Sprites[i] = SpriteImage{
					Name:   fmt.Sprintf("%s-%s", s.name, name),
					X:      0,
					Y:      -1 * lastHeight,
					Width:  width / s.pixelRatio,
					Height: height / s.pixelRatio,
				}
				lastHeight += (height + s.pixelRatio) / s.pixelRatio
			}
			if err := tmSprites.Execute(stylusFile, spriteEntry); err != nil {
				return fmt.Errorf("Cannot generate stylus for sprites %s, %v", spriteEntry, err)
			}
		}
	}
	return nil
}
Exemplo n.º 5
0
func (s *ResizeSuite) TestPreviewPdf(c *C) {
	file, err := ioutil.ReadFile("test/trunq_sprint_7-1.pdf")
	c.Assert(err, IsNil)

	buf := bytes.NewReader(file)

	preview, err := getPdfPreview(buf)
	c.Check(err, IsNil)

	previewBuf := bytes.NewReader(preview)

	image, _, err := image.Decode(previewBuf)
	c.Check(err, IsNil)
	c.Check(image.Bounds().Size().X, Equals, 1650)
	c.Check(image.Bounds().Size().Y, Equals, 1275)
}
Exemplo n.º 6
0
func AnalyzeImage(inp string) (color [3]float64, err error) {
	reader, err := os.Open(inp)
	if err != nil {
		return
	}
	defer reader.Close()
	image, _, err := image.Decode(reader)
	if err != nil {
		return
	}
	bounds := image.Bounds()
	var reds uint32
	var greens uint32
	var blues uint32
	var pixels uint32
	for i := 0; i <= bounds.Max.X; i++ {
		for j := 0; j <= bounds.Max.Y; j++ {
			pixel := image.At(i, j)
			red, green, blue, _ := pixel.RGBA()
			reds += red
			blues += blue
			greens += green
			pixels += 1
		}
	}
	color = [3]float64{float64(reds) / float64(pixels), float64(blues) / float64(pixels), float64(greens) / float64(pixels)}
	return
}
Exemplo n.º 7
0
func processFile(src io.Reader, mime string, bucket string) (*Uploadable, error) {
	if mime == "image/jpeg" || mime == "image/jpg" {
		image, format, err := fetch.GetRotatedImage(src)
		if err != nil {
			return nil, err
		}
		if format != "jpeg" {
			return nil, errors.New("You sent a bad JPEG file.")
		}

		width := image.Bounds().Size().X
		height := image.Bounds().Size().Y
		key := fileKey(bucket, width, height)

		data := new(bytes.Buffer)
		err = jpeg.Encode(data, image, nil)
		if err != nil {
			return nil, err
		}
		length := int64(data.Len())

		return &Uploadable{data, key, length}, nil

	} else {
		raw, err := ioutil.ReadAll(src)
		if err != nil {
			return nil, err
		}

		data := bytes.NewReader(raw)
		length := int64(data.Len())
		image, _, err := image.Decode(data)
		if err != nil {
			return nil, err
		}

		width := image.Bounds().Size().X
		height := image.Bounds().Size().Y
		key := fileKey(bucket, width, height)

		data.Seek(0, 0)

		return &Uploadable{data, key, length}, nil
	}
}
Exemplo n.º 8
0
func (s *ResizeSuite) TestResizeOversizedImageSquare(c *C) {
	file, err := ioutil.ReadFile("test/awesome-small.jpg")
	c.Assert(err, IsNil)

	ctx := &fetch.CacheContext{
		Width: 400,
		Crop:  true,
	}

	buf := bytes.NewReader(file)
	resized, err := fetch.Resize(buf, ctx)
	c.Check(err, IsNil)

	image, _, err := image.Decode(resized)
	c.Check(err, IsNil)
	c.Check(image.Bounds().Size().X, Equals, 150)
	c.Check(image.Bounds().Size().Y, Equals, 150)
}
Exemplo n.º 9
0
func TestHandler(t *testing.T) {
	assert, p, w := setup(t)
	server := setupUpstreamServer("test/images/gopher.png")
	defer server.Close()

	url := "https://front.com?url=" + server.URL
	req, _ := http.NewRequest("GET", url, nil)

	p.handler(w, req)

	assert.Equal(w.Code, 200, "status should be ok")
	assert.Equal(w.HeaderMap.Get("Content-Type"), "image/png")
	assert.NotEmpty(w.Body)

	image, _, _ := image.Decode((w.Body))
	// Should be original size
	assert.Equal(image.Bounds().Dx(), 250, "width should be 250")
	assert.Equal(image.Bounds().Dy(), 340, "height should be 340")
}
Exemplo n.º 10
0
func (s *ResizeSuite) TestResizeNoExifImage(c *C) {
	file, err := ioutil.ReadFile("test/AWESOME.jpg")
	c.Assert(err, IsNil)

	for width, height := range noExifSizes {
		ctx := &fetch.CacheContext{
			Width: width,
		}

		buf := bytes.NewReader(file)
		resized, err := fetch.Resize(buf, ctx)
		c.Check(err, IsNil)

		image, _, err := image.Decode(resized)
		c.Check(err, IsNil)
		c.Check(image.Bounds().Size().X, Equals, width)
		c.Check(image.Bounds().Size().Y, Equals, height)
	}
}
Exemplo n.º 11
0
func TestHandlerWithSizeParams(t *testing.T) {
	assert, p, w := setup(t)
	server := setupUpstreamServer("test/images/gopher.png")
	defer server.Close()

	url := "https://front.com?width=500&height=100&url=" + server.URL
	req, _ := http.NewRequest("GET", url, nil)

	p.handler(w, req)

	assert.Equal(w.Code, 200, "status should be ok")
	assert.Equal(w.HeaderMap.Get("Content-Type"), "image/jpeg")
	assert.NotEmpty(w.Body)

	image, _, _ := image.Decode((w.Body))
	// Should be resized
	assert.Equal(image.Bounds().Dx(), 500, "width should be 500")
	assert.Equal(image.Bounds().Dy(), 100, "height should be 100")
}
Exemplo n.º 12
0
func (s _Sprite) Build(isProduction bool) error {
	targetFolder := fmt.Sprintf("public/images/%s", s.entry)
	if err := os.MkdirAll(targetFolder, os.ModePerm|os.ModeDir); err != nil {
		return fmt.Errorf("Cannot mkdir %s, %v", targetFolder, err)
	}

	if imageItems, err := s.getImages(s.fullpath); err != nil {
		return err
	} else {
		files := make([]*os.File, len(imageItems))
		images := make([]_ImageItem, len(imageItems))
		width, height := 0, 0
		for i, imgItem := range imageItems {
			if file, err := os.Open(imgItem.fullpath); err != nil {
				return fmt.Errorf("Cannot open image file: %s, %v", imgItem.fullpath, err)
			} else {
				if image, _, err := image.Decode(file); err != nil {
					return err
				} else {
					files[i] = file
					images[i] = _ImageItem{imgItem, image}
					height += image.Bounds().Dy() + s.pixelRatio
					if width < image.Bounds().Dx() {
						width = image.Bounds().Dx()
					}
				}
			}
		}

		spriteImage := image.NewNRGBA(image.Rect(0, 0, width, height))
		yOffset := 0
		for i := range images {
			files[i].Close()
			newBounds := image.Rect(0, yOffset, images[i].Bounds().Dx(), yOffset+images[i].Bounds().Dy())
			draw.Draw(spriteImage, newBounds, images[i], image.Point{0, 0}, draw.Src)
			yOffset += images[i].Bounds().Dy() + s.pixelRatio
		}
		return s.save(spriteImage, images, width, height)
	}
	return nil
}
Exemplo n.º 13
0
func main() {
	if len(os.Args) <= 1 {
		fmt.Fprint(os.Stderr, "usage: go-colorweave <filename>")
		return
	}
	reader, err := os.Open(os.Args[1])
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
	}
	defer reader.Close()

	image, _, err := image.Decode(reader)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s", err)
	}

	// Resize the image to smaller scale for faster computation
	image = resize.Resize(100, 0, image, resize.Bilinear)
	bounds := image.Bounds()

	ColorCounter := make(map[string]int)
	Limit := 5 // Limiting how many colors to be displayed in output
	TotalPixels := bounds.Max.X * bounds.Max.Y

	for i := 0; i <= bounds.Max.X; i++ {
		for j := 0; j <= bounds.Max.Y; j++ {
			pixel := image.At(i, j)
			red, green, blue, _ := pixel.RGBA()
			RGBTuple := []int{int(red / 255), int(green / 255), int(blue / 255)}
			ColorName := FindClosestColor(RGBTuple, "css21")
			_, present := ColorCounter[ColorName]
			if present {
				ColorCounter[ColorName] += 1
			} else {
				ColorCounter[ColorName] = 1
			}
		}
	}

	// Sort by the frequency of each color
	keys := make([]int, 0, len(ColorCounter))
	for _, val := range ColorCounter {
		keys = append(keys, val)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(keys)))

	ReverseColorCounter := ReverseMap(ColorCounter)

	// Display the top N dominant colors from the image
	for _, val := range keys[:Limit] {
		fmt.Printf("%s %.2f%%\n", ReverseColorCounter[val], ((float64(val) / float64(TotalPixels)) * 100))
	}
}
Exemplo n.º 14
0
// ReadImage loads an image from an image file and generates a vector which represents its black and
// white pixels.
func ReadImage(path string) (*Image, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	image, _, err := image.Decode(file)
	if err != nil {
		return nil, err
	}
	res := &Image{
		Vector: make([]float64, image.Bounds().Dx()*image.Bounds().Dy()),
		Width:  image.Bounds().Dx(),
		Height: image.Bounds().Dy(),
	}
	idx := 0
	for y := 0; y < image.Bounds().Dy(); y++ {
		for x := 0; x < image.Bounds().Dx(); x++ {
			r, g, b, _ := image.At(x, y).RGBA()
			black := float64(r+g+b) / float64(0xffff*3)
			res.Vector[idx] = black
			idx++
		}
	}
	return res, nil
}
Exemplo n.º 15
0
func Resize(src io.Reader, c *CacheContext) (io.Reader, error) {
	raw, err := ioutil.ReadAll(src)
	if err != nil {
		return nil, err
	}

	options := vips.Options{
		Width:        c.Width,
		Crop:         true,
		Extend:       vips.EXTEND_WHITE,
		Interpolator: vips.BILINEAR,
		Gravity:      vips.CENTRE,
		Quality:      80,
	}

	if c.Crop {
		data := bytes.NewReader(raw)

		image, _, err := image.Decode(data)
		if err != nil {
			return nil, err
		}

		minDimension := int(math.Min(float64(image.Bounds().Size().X), float64(image.Bounds().Size().Y)))

		if minDimension < options.Width || options.Width == 0 {
			options.Width = minDimension
		}

		options.Height = options.Width
	}

	res, err := vips.Resize(raw, options)
	if err != nil {
		return nil, err
	}

	return bytes.NewBuffer(res), err
}
Exemplo n.º 16
0
func main() {
	for i := 0; i < 2; i++ {
		bench_total = 0

		image := openImage("image.png")
		grayscale := newGray(image.Bounds())
		if i == 0 {
			convertDraw(image, grayscale)
		} else {
			convertLoop(image, grayscale)
		}
		saveImage(grayscale, "go_output.png")

		printSummary()
		fmt.Println()
	}
}
Exemplo n.º 17
0
func (s *ResizeSuite) TestResizeAnimatedGif(c *C) {
	file, err := ioutil.ReadFile("test/animated.gif")
	c.Assert(err, IsNil)

	for width, _ := range sizes {
		ctx := &fetch.CacheContext{
			Width: width,
		}

		buf := bytes.NewReader(file)
		resized, err := fetch.ResizeGif(buf, ctx)
		c.Check(err, IsNil)

		image, _, err := image.Decode(resized)
		c.Check(err, IsNil)
		c.Check(image.Bounds().Size().X, Equals, width)
	}
}
Exemplo n.º 18
0
// Load image data
func LoadImage(imageFileName string) image.Image {

	file, err := os.Open(imageFileName)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	image, format, err := image.Decode(file)
	if err != nil {
		panic(err)
	}

	fmt.Println("Loaded", format, "Size", image.Bounds())

	return image
	//return SobelImage(image) // turns out that runnign edge detection first does NOT help the image, it only removes information from the picture
}
Exemplo n.º 19
0
func decodeImage(file string) {
	info := ""

	reader, err := os.Open(file)
	if err != nil {
		fmt.Printf("--- Open error ---\n")
	}
	defer reader.Close()

	//image contain RGBA colors
	image, _, err := image.Decode(reader)
	if err != nil {
		fmt.Printf("--- Decode error ---\n")
	}

	bound := image.Bounds()

	var msg []string
	for i := 0; i < bound.Max.Y; i++ {
		for j := 0; j < bound.Max.X; j++ {
			pixel := image.At(j, i)
			r, _, _, _ := pixel.RGBA()

			if r == 0 {
				info = info + black
			} else {
				info = info + red
			}
		}

		num, err := strconv.ParseInt(info, 2, 0)
		if err != nil {
			panic(err)
		}

		msg = append(msg, string(int(num)))
		info = ""
	}

	fmt.Printf("\nMessage:\n%s\n\n", strings.Join(msg, ""))
}
Exemplo n.º 20
0
func streamRecording(w http.ResponseWriter, f http.File) {
	updateChan, _ := readFile(f)
	imageChan := make(chan image.Image, 10)

	// gorountine to rebuild the images
	go func() {
		var X, Y int

		prev := time.Now()
		img := image.NewRGBA(image.Rect(0, 0, X, Y))

		// for each jpeg image
		for update := range updateChan {
			// Check if the resolution has changed
			last := update.Rectangles[len(update.Rectangles)-1]
			if last.EncodingType == DesktopSize || X == 0 || Y == 0 {
				X = last.Rect.Max.X
				Y = last.Rect.Max.Y
			}

			nimg := image.NewRGBA(image.Rect(0, 0, X, Y))

			// Copy in the previous image
			dr := image.Rectangle{img.Rect.Min, img.Rect.Max}
			draw.Draw(nimg, dr, img, img.Rect.Min, draw.Src)

			for _, r := range update.Rectangles {
				dr := image.Rectangle{r.Rect.Min, r.Rect.Max}
				log.Debug("drawing in rectangle at %#v\n", dr)
				draw.Draw(nimg, dr, r, r.Rect.Min, draw.Src)
			}

			offset := time.Now().Sub(prev).Nanoseconds()
			prev = time.Now()

			if offset < update.Offset {
				// Sleep until the next image should be served
				time.Sleep(time.Duration(update.Offset - offset))
			} else {
				log.Debugln("warning: longer to replay images than record them")
			}

			imageChan <- nimg
			img = nimg
		}

		close(imageChan)
	}()

	mh := make(textproto.MIMEHeader)
	mh.Set("Content-Type", "image/jpeg")

	m := multipart.NewWriter(w)
	defer m.Close()

	h := w.Header()
	boundary := m.Boundary()
	h.Set("Content-type", fmt.Sprintf("multipart/x-mixed-replace; boundary=%s", boundary))

	// encode and send the image
	var buf bytes.Buffer
	for image := range imageChan {
		buf.Reset()

		log.Debug("writing image: %v", image.Bounds())
		err := jpeg.Encode(&buf, image, nil)
		if err != nil {
			log.Error("unable to encode jpeg: %v", err)
			break
		}

		mh.Set("Content-length", fmt.Sprintf("%d", buf.Len()))
		fm, err := m.CreatePart(mh)
		if err != nil {
			log.Error("unable to create multipart: %v", err)
			return
		}
		_, err = io.Copy(fm, &buf)
		if err != nil {
			log.Error("unable to write multipart: %v", err)
			break
		}
	}
}
Exemplo n.º 21
0
func processImage(src io.Reader, mime string, bucket string) (*url.URL, *url.URL, error) {
	if mime == "image/jpeg" || mime == "image/jpg" {
		image, format, err := fetch.GetRotatedImage(src)
		if err != nil {
			return nil, nil, err
		}
		if format != "jpeg" {
			return nil, nil, errors.New("You sent a bad JPEG file.")
		}

		width := image.Bounds().Size().X
		height := image.Bounds().Size().Y
		key := fileKey(bucket, width, height, "jpg")

		data := new(bytes.Buffer)
		err = jpeg.Encode(data, image, nil)
		if err != nil {
			return nil, nil, err
		}
		length := int64(data.Len())

		// Upload original file to S3
		err = storage.PutReader(bucket, key, data, length, mime)
		if err != nil {
			return nil, nil, err
		}

		uri := fileUri(bucket, key)

		return uri, uri, nil

	} else {
		raw, err := ioutil.ReadAll(src)
		if err != nil {
			return nil, nil, err
		}

		data := bytes.NewReader(raw)
		length := int64(data.Len())
		image, format, err := image.Decode(data)
		if err != nil {
			return nil, nil, err
		}

		width := image.Bounds().Size().X
		height := image.Bounds().Size().Y
		key := fileKey(bucket, width, height, format)

		data.Seek(0, 0)

		// Upload original file to S3
		err = storage.PutReader(bucket, key, data, length, mime)
		if err != nil {
			return nil, nil, err
		}

		uri := fileUri(bucket, key)

		return uri, uri, nil
	}
}