代码如下:
```go
func LoadImage(path string) (img image.Image, err error) {
f, err := os.Open(path)
if err != nil {
log.Fatal(err)
return
}
log.Println(f)
defer f.Close()
img, _, err = image.Decode(bufio.NewReader(f))
log.Println(img)
return
}
```
返回的结果如下:
```go
2015/07/07 11:26:29 &{0x11b1a1c0}
2015/07/07 11:26:29 nil
2015/07/07 11:26:29 image: unknown format
```
请问,这是什么原因呢?我查看官方源代码Decode的测试代码也是这么写的呀?
```go
func decode(filename string) (image.Image, string, error) {
f, err := os.Open(filename)
if err != nil {
return nil, "", err
}
defer f.Close()
return image.Decode(bufio.NewReader(f))
}
```
orz...总算保持代码格式了。。。。
全部代码,搞不明白哪里有问题:
```go
package main
import (
"code.google.com/p/freetype-go/freetype"
"image"
"image/color"
"image/draw"
"image/png"
"io/ioutil"
"log"
"os"
"strings"
"time"
)
const (
DefaultFontSize = 30
DefaultDpi = 72
)
func main() {
log.Println("true or false ? ", PrintImage("Hello World", 14))
}
func PrintImage(text string, fontSize float64) bool {
im, err := drawStringImage(text, fontSize)
if err != nil {
log.Fatalln(err)
return false
}
dst, err := os.Create("image/test3_o.png")
if err != nil {
log.Fatalln(err)
return false
}
defer dst.Close()
err = png.Encode(dst, im)
if err != nil {
log.Fatalln(err)
return false
}
return true
}
func drawStringImage(text string, fontSize float64) (image.Image, error) {
fImg1, _ := os.Open("./image/search_banner.png")
defer fImg1.Close()
log.Println(fImg1)
img1, err := png.Decode(fImg1)
if err != nil {
log.Fatal(err)
}
rgba := image.NewRGBA(image.Rect(0, 0, 360, 200))
draw.Draw(rgba, rgba.Bounds(), img1, image.Point{0, 0}, draw.Src)
fontBytes, err := ioutil.ReadFile("msyh.ttf")
if err != nil {
return nil, err
}
font, err := freetype.ParseFont(fontBytes)
if err != nil {
return nil, err
}
fg := image.Black
c := freetype.NewContext()
c.SetDPI(DefaultDpi)
c.SetFont(font)
c.SetFontSize(fontSize)
c.SetClip(rgba.Bounds())
c.SetDst(rgba)
c.SetSrc(fg)
// Draw the text.
pt := freetype.Pt(10, 10+int(c.PointToFix32(12)>>8))
for _, s := range strings.Split(text, "\r\n") {
_, err = c.DrawString(s, pt)
pt.Y += c.PointToFix32(fontSize * 1.5)
}
gy := image.NewUniform(color.RGBA{uint8(0), uint8(0), uint8(0), 255})
c.SetSrc(gy)
fontSize = 15
now := time.Now().Format("01月02日 15:04")
for _, s := range strings.Split(now, "\r\n") {
_, err = c.DrawString(s, pt)
pt.Y += c.PointToFix32(fontSize * 1.5)
}
return rgba, nil
}
```
#4
更多评论