Exemple #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()
}
Exemple #2
1
// decoder reads an image from r and modifies the image as defined by opts.
// swapDimensions indicates the decoded image will be rotated after being
// returned, and when interpreting opts, the post-rotation dimensions should
// be considered.
// The decoded image is returned in im. The registered name of the decoder
// used is returned in format. If the image was not successfully decoded, err
// will be non-nil.  If the decoded image was made smaller, needRescale will
// be true.
func decode(r io.Reader, opts *DecodeOpts, swapDimensions bool) (im image.Image, format string, err error, needRescale bool) {
	if opts == nil {
		// Fall-back to normal decode.
		im, format, err = image.Decode(r)
		return im, format, err, false
	}

	var buf bytes.Buffer
	tr := io.TeeReader(r, &buf)
	ic, format, err := image.DecodeConfig(tr)
	if err != nil {
		return nil, "", err, false
	}

	mr := io.MultiReader(&buf, r)
	b := image.Rect(0, 0, ic.Width, ic.Height)
	sw, sh, needRescale := opts.rescaleDimensions(b, swapDimensions)
	if !needRescale {
		im, format, err = image.Decode(mr)
		return im, format, err, false
	}

	imageDebug(fmt.Sprintf("Resizing from %dx%d -> %dx%d", ic.Width, ic.Height, sw, sh))
	if format == "cr2" {
		// Replace mr with an io.Reader to the JPEG thumbnail embedded in a
		// CR2 image.
		if mr, err = cr2.NewReader(mr); err != nil {
			return nil, "", err, false
		}
		format = "jpeg"
	}

	if format == "jpeg" && fastjpeg.Available() {
		factor := fastjpeg.Factor(ic.Width, ic.Height, sw, sh)
		if factor > 1 {
			var buf bytes.Buffer
			tr := io.TeeReader(mr, &buf)
			im, err = fastjpeg.DecodeDownsample(tr, factor)
			switch err.(type) {
			case fastjpeg.DjpegFailedError:
				log.Printf("Retrying with jpeg.Decode, because djpeg failed with: %v", err)
				im, err = jpeg.Decode(io.MultiReader(&buf, mr))
			case nil:
				// fallthrough to rescale() below.
			default:
				return nil, format, err, false
			}
			return rescale(im, sw, sh), format, err, true
		}
	}

	// Fall-back to normal decode.
	im, format, err = image.Decode(mr)
	if err != nil {
		return nil, "", err, false
	}
	return rescale(im, sw, sh), format, err, needRescale
}
Exemple #3
0
func CheckImage(t TesterLight, img []byte, sample []byte) {
	i1, _, err := image.Decode(bytes.NewReader(img))
	if err != nil {
		t.Fatal(err)
	}

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

	if !i1.Bounds().Eq(i2.Bounds()) {
		t.Fatalf("Different image bounds: %v and %v", i1.Bounds(), i2.Bounds())
	}

	bounds := i1.Bounds()
	for x := bounds.Min.X; x < bounds.Max.Y; x++ {
		for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
			c1 := i1.At(x, y)
			c2 := i2.At(x, y)
			if !CmpColors(c1, c2, 30) {
				t.Fatalf("Different colors at (%v, %v): %v vs %v", x, y, c1, c2)
			}
		}
	}
}
Exemple #4
0
func TestPHA(t *testing.T) {
	// Load picture from file.
	infile, err := os.Open("./testdata/pic_output.png")
	if err != nil {
		t.Errorf("Load picture: %s.", err)
	}

	// Decode picture.
	srcImg, _, err := image.Decode(infile)
	infile.Close()
	if err != nil {
		t.Errorf("Decode picture: %s.", err)
	}

	fg := PHA(srcImg)
	fmt.Println("Fingerprint:", fg)

	// Load picture2 from file.
	infile, err = os.Open("./testdata/pic_output2.jpg")
	if err != nil {
		t.Errorf("Load picture2: %s.", err)
	}

	// Decode picture.
	srcImg, _, err = image.Decode(infile)
	infile.Close()
	if err != nil {
		t.Errorf("Decode picture2: %s.", err)
	}

	fg2 := PHA(srcImg)
	fmt.Println("Fingerprint:", fg2)

	fmt.Println("Diff num:", CompareDiff(fg, fg2))
}
Exemple #5
0
func pixels(source, target string) bool {
	sourcefile, err := os.Open(source)
	checkerror(err)
	defer sourcefile.Close()

	targetfile, err := os.Open(target)
	checkerror(err)
	defer targetfile.Close()

	sourceimage, _, err := image.Decode(sourcefile)
	targetimage, _, err := image.Decode(targetfile)

	sourcebounds := sourceimage.Bounds()
	targetbounds := targetimage.Bounds()

	if (sourcebounds.Min.Y != targetbounds.Min.Y) || (sourcebounds.Min.X != targetbounds.Min.X) || (sourcebounds.Max.Y != targetbounds.Max.Y) || (sourcebounds.Max.X != targetbounds.Max.X) {
		return false
		// log.Fatalln("Images are not the same size pixel-wise!")
	}

	for y := sourcebounds.Min.Y; y < sourcebounds.Max.Y; y++ {
		for x := sourcebounds.Min.X; x < sourcebounds.Max.X; x++ {
			sr, sg, sb, sa := sourceimage.At(x, y).RGBA()
			tr, tg, tb, ta := targetimage.At(x, y).RGBA()

			if (sr != tr) || (sg != tg) || (sb != tb) || (sa != ta) {
				return false
				// log.Fatalln("Ah! They are not the same!", x, y)
			}
		}
	}

	return true
}
Exemple #6
0
func TestReplaceImage(t *testing.T) {
	proxy := goproxy.NewProxyHttpServer()

	panda := getImage("test_data/panda.png", t)
	football := getImage("test_data/football.png", t)

	proxy.HandleResponse(goproxy.UrlIsIn("/test_data/panda.png")(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image {
		return football
	})))

	proxy.HandleResponse(goproxy.UrlIsIn("/test_data/football.png")(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image {
		return panda
	})))

	client, l := oneShotProxy(proxy, t)
	defer l.Close()

	imgByPandaReq, _, err := image.Decode(bytes.NewReader(getOrFail(localFile("test_data/panda.png"), client, t)))
	fatalOnErr(err, "decode panda", t)
	compareImage(football, imgByPandaReq, t)

	imgByFootballReq, _, err := image.Decode(bytes.NewReader(getOrFail(localFile("test_data/football.png"), client, t)))
	fatalOnErr(err, "decode football", t)
	compareImage(panda, imgByFootballReq, t)
}
Exemple #7
0
func DrawLogo(qrPng []byte, logo string, logoBgColor color.Color) []byte {

	if logo != "" {
		// println(logo)
		resp, err := http.Get(logo)

		if err != nil {
			fmt.Printf("Logo Error=%s\n", err.Error())
			// println(resp)
		} else {

			logoImg, _, _ := image.Decode(resp.Body)
			qrImg, _, _ := image.Decode(bytes.NewReader(qrPng))
			pb := qrImg.Bounds()
			logoImg = resize.Resize(uint(pb.Dx()/4), uint(pb.Dy()/4), logoImg, resize.Lanczos3)
			logoBgImg := image.NewRGBA(image.Rect(0, 0, logoImg.Bounds().Dx()+2, logoImg.Bounds().Dy()+2))
			draw.Draw(logoBgImg, logoBgImg.Bounds(), &image.Uniform{color.White}, image.Point{}, draw.Src)
			draw.Draw(logoBgImg, logoImg.Bounds(), logoImg, image.Point{-1, -1}, draw.Over)

			offsetX := (pb.Dx() - logoBgImg.Bounds().Dx()) / 2
			newImg := image.NewRGBA(pb)
			draw.Draw(newImg, pb, qrImg, image.Point{}, draw.Src)
			draw.Draw(newImg, newImg.Bounds(), logoBgImg, image.Point{-offsetX, -offsetX}, draw.Over)
			// println(logoImg)
			buf := new(bytes.Buffer)
			err = png.Encode(buf, newImg)
			// send_s3 := buf.Bytes()
			return buf.Bytes()

		}
	}
	return qrPng
}
Exemple #8
0
func TestImageHandler(t *testing.T) {
	client, proxy, l := oneShotProxy(t)
	defer l.Close()

	football := getImage("test_data/football.png", t)

	proxy.OnResponse(goproxy.UrlIs("/test_data/panda.png")).Do(goproxy_image.HandleImage(func(img image.Image, ctx *goproxy.ProxyCtx) image.Image {
		return football
	}))

	resp, err := client.Get(localFile("test_data/panda.png"))
	if err != nil {
		t.Fatal("Cannot get panda.png", err)
	}

	img, _, err := image.Decode(resp.Body)
	if err != nil {
		t.Error("decode", err)
	} else {
		compareImage(football, img, t)
	}

	// and again
	resp, err = client.Get(localFile("test_data/panda.png"))
	if err != nil {
		t.Fatal("Cannot get panda.png", err)
	}

	img, _, err = image.Decode(resp.Body)
	if err != nil {
		t.Error("decode", err)
	} else {
		compareImage(football, img, t)
	}
}
Exemple #9
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)
}
Exemple #10
0
func LoadImage(data interface{}) Image {
	var m image.Image

	switch data := data.(type) {
	default:
		log.Fatal("NewTexture needs a string or io.Reader")
	case string:
		file, err := os.Open(data)
		if err != nil {
			log.Fatal(err)
		}
		defer file.Close()
		img, _, err := image.Decode(file)
		if err != nil {
			log.Fatal(err)
		}
		m = img
	case io.Reader:
		img, _, err := image.Decode(data)
		if err != nil {
			log.Fatal(err)
		}
		m = img
	case image.Image:
		m = data
	}

	b := m.Bounds()
	newm := image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
	draw.Draw(newm, newm.Bounds(), m, b.Min, draw.Src)

	return &ImageObject{newm}
}
Exemple #11
0
func CheckImg(src, tgt io.Reader) (int, error) {
	image1, format1, err1 := image.Decode(src)
	image2, format2, err2 := image.Decode(tgt)
	if err1 != nil || err2 != nil {
		return 1, errors.New(fmt.Sprintf("From Servier error : %v , From Local error : %v \n", err1, err2))
	}
	if format2 != format1 {
		return 2, errors.New("Unmatched format!")
	}
	if image1.Bounds() != image2.Bounds() {
		return 3, errors.New("Unmatched bounds")
	}

	total, miss := 0, 0
	for i := image1.Bounds().Min.X; i <= image1.Bounds().Max.X; i++ {
		for j := image1.Bounds().Min.Y; j <= image1.Bounds().Max.Y; j++ {
			total++
			r1, g1, b1, a1 := image1.At(i, j).RGBA()
			r2, g2, b2, a2 := image2.At(i, j).RGBA()
			if !approachTo(r1, r2) || !approachTo(g1, g2) || !approachTo(b1, b2) || !approachTo(a1, a2) {
				return 4, errors.New("Differs two much!")
			}
			if r1 != r2 || g1 != g2 || b1 != b2 || a1 != a2 {
				miss++
			}
		}
	}
	if miss > total/20 {
		return 4, errors.New("Missed too much!")
	}
	return 0, nil
}
func (s *ResizeSuite) TestOriginalColdCache(c *C) {
	// Open the file once to get it's size
	file, err := ioutil.ReadFile("test/exif_test_img.jpg")
	c.Assert(err, IsNil)

	img, _, err := image.Decode(bytes.NewReader(file))
	c.Assert(err, IsNil)

	// Since this image should be rotated, height should equal
	// width after it's uploaded.
	originalSize := img.Bounds().Size().Y

	// A single, unresized image is in the database/store
	ctx, err := s.insertMockImage()
	c.Assert(err, IsNil)

	// Run the image resize request
	data, err := fetch.ImageData(storage, ctx)
	c.Assert(err, IsNil)

	// Verify the size of the resulting byte slice
	img, _, err = image.Decode(bytes.NewReader(data))
	c.Assert(err, IsNil)
	c.Assert(img.Bounds().Size().X, Equals, originalSize)
}
Exemple #13
0
func main() {
	srcPath := os.Args[1]
	flatPath := os.Args[2]
	dstPath := os.Args[3]

	reader, err := os.Open(srcPath)
	check(err)
	src, srcFmt, err := image.Decode(reader)
	check(err)
	fmt.Println("Decoded source", srcPath, "as", srcFmt)

	reader, err = os.Open(flatPath)
	check(err)
	flat, name, err := image.Decode(reader)
	check(err)
	fmt.Println("Decoded flat", flatPath, "as", name)

	if src.Bounds() != flat.Bounds() {
		log.Fatal("Bounds not equal")
	}

	proxy := ProxyImage{src, flat}

	writer, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE, 0600)
	check(err)
	if strings.HasSuffix(dstPath, ".jpg") || strings.HasSuffix(dstPath, ".jpeg") {
		jpeg.Encode(writer, proxy, &jpeg.Options{90})
	} else if strings.HasSuffix(dstPath, ".png") {
		png.Encode(writer, proxy)
	} else {
		log.Fatal(dstPath + "does not have .jpg or .png extension")
	}
}
Exemple #14
0
func TestDecodeRawRGB(t *testing.T) {
	pnmFile := openFile(t, "testdata/test_rgb_raw.ppm")
	pngFile := openFile(t, "testdata/test_rgb.png")
	defer pngFile.Close()
	defer pnmFile.Close()
	pnmImage, format, err := image.Decode(pnmFile)
	pngImage, _, err := image.Decode(pngFile)
	pnm := pnmImage.(*image.RGBA)
	png := pngImage.(*image.RGBA)

	if err != nil {
		t.Fatal(err)
	}

	if format != "ppm raw (rgb)" {
		t.Fatal("Unexpected format:", format, "expecting ppm raw (rgb)")
	}

	if len(png.Pix) != len(pnm.Pix) {
		t.Fatal("Wrong pixel count:", len(pnm.Pix), "expected: ", len(png.Pix))
	}

	for i := 0; i < len(png.Pix); i++ {
		//t.Log("(", png.Pix[i], ",", pnm.Pix[i], ")")
		if png.Pix[i] != pnm.Pix[i] {
			t.Fatal("Incorrect pixel at position", i, "found", pnm.Pix[i], "but expected", png.Pix[i])
		}
	}

}
Exemple #15
0
func main() {
	file, err := os.Open("android.png")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	a, _, err := image.Decode(file)

	//load go icon image
	file2, err := os.Open("go.png")
	if err != nil {
		log.Fatal(err)
	}
	defer file2.Close()
	g, _, err := image.Decode(file2)

	if err != nil {
		log.Fatal(err)
	}

	ar := a.Bounds()
	w, h, x := ar.Dx(), ar.Dy(), 30.0
	i := image.NewRGBA(image.Rect(0, 0, w, h))
	draw.Draw(i, ar, a, ar.Min, draw.Src)

	tr := draw2d.NewRotationMatrix(x * (math.Pi / 180.0))
	draw2d.DrawImage(g, i, tr, draw.Over, draw2d.LinearFilter)
	saveToPngFile("Test2.png", i)
}
Exemple #16
0
func main() {
	heightInt, widthInt, _ := pty.Getsize(os.Stdout)

	var width uint
	var height uint

	// The three subtracted lines is to have room for command, file name and prompt after explosion
	flag.UintVar(&width, "w", uint(widthInt), "Maximum width of output in number of columns")
	flag.UintVar(&height, "h", uint((heightInt-3)*2), "Maximum height of output in number of half lines")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s [options] [file | - ...]\n\n", os.Args[0])
		fmt.Fprintln(os.Stderr, "  Specify \"-\" or just noting to read from stdin.")
		fmt.Fprintln(os.Stderr)
		fmt.Fprintln(os.Stderr, "Options:")
		flag.PrintDefaults()
	}
	flag.Parse()

	filenames := flag.Args()
	if len(filenames) == 0 {
		fmt.Println("stdin:")
		sourceImage, _, err := image.Decode(os.Stdin)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error:", err)
		} else {
			printImage(sourceImage, width, height)
		}
	} else {
		for i, filename := range filenames {
			if i > 0 {
				fmt.Println()
			}

			var file *os.File
			var err error

			if filename == "-" {
				fmt.Println("stdin:")
				file = os.Stdin
			} else {
				fmt.Printf("%s:\n", filename)
				file, err = os.Open(filename)
				if err != nil {
					fmt.Fprintln(os.Stderr, "Error:", err)
					continue
				}
			}

			sourceImage, _, err := image.Decode(file)
			_ = file.Close()
			if err != nil {
				fmt.Fprintln(os.Stderr, "Error:", err)
				continue
			}

			printImage(sourceImage, width, height)
		}
	}
}
Exemple #17
0
func loadTextures() []sprite.SubTex {
	a, err := asset.Open("cards.jpeg")
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	img, _, err := image.Decode(a)
	if err != nil {
		log.Fatal(err)
	}
	t, err := eng.LoadTexture(img)
	if err != nil {
		log.Fatal(err)
	}

	a2, err := asset.Open("dropTarget.jpeg")
	if err != nil {
		log.Fatal(err)
	}
	defer a2.Close()

	img2, _, err := image.Decode(a2)
	if err != nil {
		log.Fatal(err)
	}
	t2, err := eng.LoadTexture(img2)
	if err != nil {
		log.Fatal(err)
	}

	a3, err := asset.Open("deck.jpeg")
	if err != nil {
		log.Fatal(err)
	}
	defer a3.Close()

	img3, _, err := image.Decode(a3)
	if err != nil {
		log.Fatal(err)
	}
	t3, err := eng.LoadTexture(img3)
	if err != nil {
		log.Fatal(err)
	}

	return []sprite.SubTex{
		card1:      sprite.SubTex{t, image.Rect(15, 15, 190, 260)},
		card2:      sprite.SubTex{t, image.Rect(195, 60, 370, 305)},
		card3:      sprite.SubTex{t, image.Rect(375, 107, 550, 350)},
		card4:      sprite.SubTex{t, image.Rect(555, 135, 730, 377)},
		dropTarget: sprite.SubTex{t2, image.Rect(0, 0, 766, 620)},
		draw:       sprite.SubTex{t3, image.Rect(0, 0, 1506/2, 1052)},
		discard:    sprite.SubTex{t3, image.Rect(1506/2, 0, 1506, 1052)},
	}
}
Exemple #18
0
// BuildImage builds a new image with 4 square images and overlays
// numbers on top (translucent). It sends to S3 and returns the public
// URL.
func (c *Challenge) BuildImage(profileURLs []string) ([]byte, error) {
	var profileImgs []image.Image
	for _, url := range profileURLs {
		resp, err := http.Get(url)
		if err != nil {
			return nil, fmt.Errorf("Couldn't get avatar: %s", err)
		}
		defer resp.Body.Close()

		cnt, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return nil, fmt.Errorf("couldn't read avatar body: %s", err)
		}

		img, _, err := image.Decode(bytes.NewBuffer(cnt))
		if err != nil {
			return nil, fmt.Errorf("decoding image: %s", err)
		}

		profileImgs = append(profileImgs, img)
	}

	numbersImage, _, _ := image.Decode(bytes.NewBuffer(numbersPNG))

	// for 4 images
	finalImage := image.NewRGBA(image.Rect(0, 0, 192+192, 192+192))
	mask := &image.Uniform{color.RGBA{0, 0, 100, 100}}

	// First
	draw.Draw(finalImage, image.Rect(0, 0, 192, 192), profileImgs[0], image.Point{0, 0}, draw.Over)
	draw.DrawMask(finalImage, image.Rect(0, 0, 64, 64), numbersImage, numbersPositions[1].Min, mask, image.Point{0, 0}, draw.Over)

	// Second
	draw.Draw(finalImage, image.Rect(192, 0, 192*2, 192), profileImgs[1], image.Point{0, 0}, draw.Over)
	draw.DrawMask(finalImage, image.Rect(192, 0, 192+64, 64), numbersImage, numbersPositions[2].Min, mask, image.Point{0, 0}, draw.Over)

	// Third
	draw.Draw(finalImage, image.Rect(0, 192, 192, 192*2), profileImgs[2], image.Point{0, 0}, draw.Over)
	draw.DrawMask(finalImage, image.Rect(0, 192, 64, 192+64), numbersImage, numbersPositions[3].Min, mask, image.Point{0, 0}, draw.Over)

	// Fourth
	draw.Draw(finalImage, image.Rect(192, 192, 192*2, 192*2), profileImgs[3], image.Point{0, 0}, draw.Over)
	draw.DrawMask(finalImage, image.Rect(192, 192, 192+64, 192+64), numbersImage, numbersPositions[4].Min, mask, image.Point{0, 0}, draw.Over)

	buf := &bytes.Buffer{}
	png.Encode(buf, finalImage)

	return buf.Bytes(), nil

	//return "https://avatars.slack-edge.com/2014-12-08/3167931031_42ef453717f47b15aa3b_192.jpg", nil
}
Exemple #19
0
func TestBasic(t *testing.T) {
	req := Client.NewRequest(t, "GET", "/350x150", nil)
	req.EnableRecording("placehold.apib")
	res := Client.Do(t, req, 200)
	img, format, err := image.Decode(bytes.NewReader(res.Body))
	assert.NoError(t, err)
	assert.Equal(t, "png", format)
	assert.Equal(t, "(350,150)", img.Bounds().Max.String())

	res = Client.Get(t, "/350x150.jpeg", 200)
	img, format, err = image.Decode(bytes.NewReader(res.Body))
	assert.NoError(t, err)
	assert.Equal(t, "jpeg", format)
	assert.Equal(t, "(350,150)", img.Bounds().Max.String())
}
Exemple #20
0
func TestResizeEmoji(t *testing.T) {
	// try to resize a jpeg image within MaxEmojiWidth and MaxEmojiHeight
	small_img_data := createTestJpeg(t, MaxEmojiWidth, MaxEmojiHeight)
	if small_img, _, err := image.Decode(bytes.NewReader(small_img_data)); err != nil {
		t.Fatal("failed to decode jpeg bytes to image.Image")
	} else {
		resized_img := resizeEmoji(small_img, small_img.Bounds().Dx(), small_img.Bounds().Dy())
		if resized_img.Bounds().Dx() > MaxEmojiWidth || resized_img.Bounds().Dy() > MaxEmojiHeight {
			t.Fatal("resized jpeg width and height should not be greater than MaxEmojiWidth or MaxEmojiHeight")
		}
		if resized_img != small_img {
			t.Fatal("should've returned small_img itself")
		}
	}
	// try to resize a jpeg image
	jpeg_data := createTestJpeg(t, 256, 256)
	if jpeg_img, _, err := image.Decode(bytes.NewReader(jpeg_data)); err != nil {
		t.Fatal("failed to decode jpeg bytes to image.Image")
	} else {
		resized_jpeg := resizeEmoji(jpeg_img, jpeg_img.Bounds().Dx(), jpeg_img.Bounds().Dy())
		if resized_jpeg.Bounds().Dx() > MaxEmojiWidth || resized_jpeg.Bounds().Dy() > MaxEmojiHeight {
			t.Fatal("resized jpeg width and height should not be greater than MaxEmojiWidth or MaxEmojiHeight")
		}
	}
	// try to resize a png image
	png_data := createTestJpeg(t, 256, 256)
	if png_img, _, err := image.Decode(bytes.NewReader(png_data)); err != nil {
		t.Fatal("failed to decode png bytes to image.Image")
	} else {
		resized_png := resizeEmoji(png_img, png_img.Bounds().Dx(), png_img.Bounds().Dy())
		if resized_png.Bounds().Dx() > MaxEmojiWidth || resized_png.Bounds().Dy() > MaxEmojiHeight {
			t.Fatal("resized png width and height should not be greater than MaxEmojiWidth or MaxEmojiHeight")
		}
	}
	// try to resize an animated gif
	gif_data := createTestAnimatedGif(t, 256, 256, 10)
	if gif_img, err := gif.DecodeAll(bytes.NewReader(gif_data)); err != nil {
		t.Fatal("failed to decode gif bytes to gif.GIF")
	} else {
		resized_gif := resizeEmojiGif(gif_img)
		if resized_gif.Config.Width > MaxEmojiWidth || resized_gif.Config.Height > MaxEmojiHeight {
			t.Fatal("resized gif width and height should not be greater than MaxEmojiWidth or MaxEmojiHeight")
		}
		if len(resized_gif.Image) != len(gif_img.Image) {
			t.Fatal("resized gif should have the same number of frames as original gif")
		}
	}
}
Exemple #21
0
func loadSize(ctxt *fs.Context, name string, max int) *image.RGBA {
	data, _, err := ctxt.Read("qr/upload/" + name + ".png")
	if err != nil {
		panic(err)
	}
	i, _, err := image.Decode(bytes.NewBuffer(data))
	if err != nil {
		panic(err)
	}
	b := i.Bounds()
	dx, dy := max, max
	if b.Dx() > b.Dy() {
		dy = b.Dy() * dx / b.Dx()
	} else {
		dx = b.Dx() * dy / b.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)
	}
	return irgba
}
Exemple #22
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()
}
Exemple #23
0
func NewSpriteFromImage(fileName string) *Sprite {
	reader, err := os.Open(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer reader.Close()
	m, _, err := image.Decode(reader)
	if err != nil {
		log.Fatal(err)
	}
	bounds := m.Bounds()

	if bounds.Max.Y-bounds.Min.Y != 8 {
		log.Fatal("Invalid image size")
	}

	s := NewSprite(bounds.Max.X-bounds.Min.X, bounds.Max.Y-bounds.Min.Y)

	for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
		for x := bounds.Min.X; x < bounds.Max.X; x++ {
			r, g, b, _ := m.At(x, y).RGBA()
			s.SetPixel(x-bounds.Min.X, y-bounds.Min.Y, ledmatrix.RGB(int(r>>8), int(g>>8), int(b>>8)))
		}
	}

	return s
}
Exemple #24
0
func loadSprite(fileName string) Sprite {
	a, err := asset.Open(fileName)
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	img, _, err := image.Decode(a)
	if err != nil {
		log.Fatal(err)
	}
	t, err := eng.LoadTexture(img)
	if err != nil {
		log.Fatal(err)
	}

	bounds := img.Bounds()

	imgWidth := bounds.Max.X - bounds.Min.X
	imgHeight := bounds.Max.Y - bounds.Min.Y
	log.Printf("sprite %v size: %vx%v\n", fileName, imgWidth, imgHeight)

	subTex := sprite.SubTex{t, image.Rect(0, 0, imgWidth, imgHeight)}

	return Sprite{
		SubTex: subTex,
		Width:  imgWidth,
		Height: imgHeight,
	}
}
Exemple #25
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 {
	u.UseCustomAvatar = true

	img, _, err := image.Decode(bytes.NewReader(data))
	if err != nil {
		return err
	}
	m := resize.Resize(234, 234, img, resize.NearestNeighbor)

	sess := x.NewSession()
	defer sess.Close()
	if err = sess.Begin(); err != nil {
		return err
	}

	if _, err = sess.Id(u.Id).AllCols().Update(u); err != nil {
		sess.Rollback()
		return err
	}

	os.MkdirAll(setting.AvatarUploadPath, os.ModePerm)
	fw, err := os.Create(u.CustomAvatarPath())
	if err != nil {
		sess.Rollback()
		return err
	}
	defer fw.Close()
	if err = jpeg.Encode(fw, m, nil); err != nil {
		sess.Rollback()
		return err
	}

	return sess.Commit()
}
Exemple #26
0
// imgHandler is the HTTP handler for displaying images and painting
// moustaches; it handles "/img".
func imgHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	key := datastore.NewKey(c, "Image", r.FormValue("id"), 0, nil)
	im := new(Image)
	if err := datastore.Get(c, key, im); err != nil {
		writeError(w, r, err)
		return
	}

	m, _, err := image.Decode(bytes.NewBuffer(im.Data))
	if err != nil {
		writeError(w, r, err)
		return
	}

	get := func(n string) int { // helper closure
		i, _ := strconv.Atoi(r.FormValue(n))
		return i
	}
	x, y, s, d := get("x"), get("y"), get("s"), get("d")

	if x > 0 { // only draw if coordinates provided
		m = moustache(m, x, y, s, d)
	}

	b := &bytes.Buffer{}
	if err := jpeg.Encode(w, m, nil); err != nil {
		writeError(w, r, err)
		return
	}
	w.Header().Set("Content-type", "image/jpeg")
	b.WriteTo(w)
}
Exemple #27
0
func readImageFromFile(t *testing.T, srcFilename string) image.Image {
	var err error
	var srcImg image.Image

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

	srcImg, _, err = image.Decode(file)
	if err != nil {
		t.Logf("%s: %s\n", srcFilename, err.Error())
		t.FailNow()
		return nil
	}
	if srcImg == nil {
		t.Logf("%s: Decode failed\n", srcFilename)
		t.FailNow()
		return nil
	}

	return srcImg
}
Exemple #28
0
func TestRenderFile(t *testing.T) {
	m := New()
	if err := m.Load("test/map.xml"); err != nil {
		t.Fatal(err)
	}
	m.ZoomAll()

	out, err := ioutil.TempDir("", "")
	if err != nil {
		t.Fatal("unable to create temp dir")
	}
	defer os.RemoveAll(out)

	fname := filepath.Join(out, "out.png")
	if err := m.RenderToFile(RenderOpts{}, fname); err != nil {
		t.Fatal(err)
	}
	f, err := os.Open(fname)
	if err != nil {
		t.Fatal("unable to open test output", err)
	}
	defer f.Close()
	img, _, err := image.Decode(f)
	if err != nil {
		t.Fatal("unable to open test output", err)
	}
	if img.Bounds().Dx() != 800 || img.Bounds().Dy() != 600 {
		t.Error("unexpected size of output image: ", img.Bounds())
	}
}
Exemple #29
0
func ReadImages(path string) (<-chan image.Image, error) {
	dir, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer dir.Close()
	names, err := dir.Readdirnames(0)
	if err != nil {
		return nil, err
	}

	resChan := make(chan image.Image)
	go func() {
		for _, name := range names {
			imagePath := filepath.Join(path, name)
			f, err := os.Open(imagePath)
			if err != nil {
				continue
			}
			image, _, _ := image.Decode(f)
			f.Close()
			if image != nil {
				resChan <- image
			}
		}
		close(resChan)
	}()
	return resChan, nil
}
Exemple #30
0
// Image places the image in s image at (x,y) with dimensions (w,h)
func Image(x, y float64, w, h int, s string) {
	f, ferr := os.Open(s)
	if ferr != nil {
		fakeimage(x, y, w, h, s)
		return
	}
	defer f.Close()
	img, _, err := image.Decode(f)
	if err != nil {
		fakeimage(x, y, w, h, s)
		return
	}
	bounds := img.Bounds()
	minx := bounds.Min.X
	maxx := bounds.Max.X
	miny := bounds.Min.Y
	maxy := bounds.Max.Y
	data := make([]C.VGubyte, w*h*4)
	n := 0
	// println("minx", minx, "maxx", maxx, "miny", miny, "maxy", maxy)
	for y := miny; y < maxy; y++ {
		for x := minx; x < maxx; x++ {
			r, g, b, a := img.At(x, (maxy-1)-y).RGBA() // OpenVG has origin at lower left, y increasing up
			data[n] = C.VGubyte(r)
			n++
			data[n] = C.VGubyte(g)
			n++
			data[n] = C.VGubyte(b)
			n++
			data[n] = C.VGubyte(a)
			n++
		}
	}
	C.makeimage(C.VGfloat(x), C.VGfloat(y), C.int(w), C.int(h), &data[0])
}