本文整理匯總了Golang中image.Decode函數的典型用法代碼示例。如果您正苦於以下問題:Golang Decode函數的具體用法?Golang Decode怎麽用?Golang Decode使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Decode函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: waterMark
//水印
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()
}
示例2: decode
// 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
}
示例3: CheckImage
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)
}
}
}
}
示例4: TestPHA
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))
}
示例5: pixels
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
}
示例6: TestReplaceImage
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)
}
示例7: DrawLogo
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
}
示例8: TestImageHandler
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)
}
}
示例9: TestEncode
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)
}
示例10: LoadImage
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}
}
示例11: CheckImg
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
}
示例12: TestOriginalColdCache
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)
}
示例13: main
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")
}
}
示例14: TestDecodeRawRGB
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])
}
}
}
示例15: main
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)
}