准备
import (
"github.com/disintegration/imaging"
"github.com/martini-contrib/render"
"image"
"image/png"
"io/ioutil"
)
代码
单纯多图片上传,没有带文字信息
req.ParseForm()
req.ParseMultipartForm(32 << 20)
mp := req.MultipartForm
if mp == nil {
log.Println("not MultipartForm.")
return
}
fileHeaders, _ := mp.File["file"]
urls := []string{}
for _, o := range fileHeaders {
file, err := o.Open()
img, i, err := image.Decode(file)
if err != nil {
fmt.Println("err = ", err)
return
}
b := img.Bounds()
width := b.Max.X
if width > 600 {
img = imaging.Resize(img, 600, 0, imaging.Lanczos)
}
defer file.Close()
nowTime := int(time.Now().Unix())
timestr := strconv.Itoa(nowTime)
bool_fileexist := checkFileIsExist("./statics/img/topnews/news")
fmt.Println("check file 1-----------------:%s", string(nowTime))
fmt.Println("-------------------------bool_fileexist:", bool_fileexist)
host := req.Host
url := fmt.Sprintf("./statics/img/topnews/news/%s.png", timestr+i)
if bool_fileexist { //如果文件夹存在
imgfile, _ := os.Create(url)
defer imgfile.Close()
err = png.Encode(imgfile, img)
fmt.Println("文件夹存在")
} else { //不存在文件夹时 先创建文件夹再上传
fmt.Println("文件夹不存在")
err1 := os.Mkdir("./statics/img/topnews/news", os.ModePerm) //创建文件夹
if err1 != nil {
fmt.Println(err1)
return
}
fmt.Println("文件夹创建成功!")
imgfile, _ := os.Create(url)
defer imgfile.Close()
err = png.Encode(imgfile, img)
}
urls = append(urls, fmt.Sprintf("http://%s/img/topnews/news/%s.png", host, timestr+i))
}
单图片带文字信息
req.ParseForm()
pic, _, err := req.FormFile("pic")
id := req.FormValue("id")
name := req.FormValue("name")
country := req.FormValue("country")
tools.CheckErr(err)
img, i, err := image.Decode(pic)
if err != nil {
fmt.Println("err = ", err)
return
}
b := img.Bounds()
width := b.Max.X
if width > 100 {
img = imaging.Resize(img, 50, 50, imaging.Lanczos)
}
defer pic.Close()
nowTime := int(time.Now().Unix())
timestr := strconv.Itoa(nowTime)
bool_fileexist := checkFileIsExist("./statics/img/team")
fmt.Println("check file 1-----------------:%s", string(nowTime))
fmt.Println("-------------------------bool_fileexist:", bool_fileexist)
host := req.Host
url := fmt.Sprintf("./statics/img/team/%s.png", timestr)
if bool_fileexist { //如果文件夹存在
imgfile, _ := os.Create(url)
defer imgfile.Close()
err = png.Encode(imgfile, img)
fmt.Println("文件夹存在")
} else { //不存在文件夹时 先创建文件夹再上传
fmt.Println("文件夹不存在")
err1 := os.Mkdir("./statics/img/team", os.ModePerm) //创建文件夹
if err1 != nil {
fmt.Println(err1)
return
}
fmt.Println("文件夹创建成功!")
imgfile, _ := os.Create(url)
defer imgfile.Close()
err = png.Encode(imgfile, img)
}
newUrl := fmt.Sprintf("http://%s/img/team/%s.png", host, timestr+i)