利用Go语言上传图像并生成缩略图

承前文:Go语言中对图像进行缩放


//利用Go语言上传图像并生成缩略图

func upload(w http.ResponseWriter, req *http.Request, link string) {
// Upload of a new image.
// Copied from Moustachio demo.
f, _, err := req.FormFile("image")
if err != nil {
fmt.Fprintf(w, "You need to select an image to upload.\n")
return
}
defer f.Close()


i, _, err := image.Decode(f)
if err != nil {
panic(err)
}


// Convert image to 128x128 gray+alpha.
b := i.Bounds()
const max = 128
// If it's gigantic, it's more efficient to downsample first
// and then resize; resizing will smooth out the roughness.
var i1 *image.RGBA
if b.Dx() > 4*max || b.Dy() > 4*max {
w, h := 2*max, 2*max
if b.Dx() > b.Dy() {
h = b.Dy() * h / b.Dx()
} else {
w = b.Dx() * w / b.Dy()
}
i1 = resize.Resample(i, b, w, h)
} else {
// "Resample" to same size, just to convert to RGBA.
i1 = resize.Resample(i, b, b.Dx(), b.Dy())
}
b = i1.Bounds()


// Encode to PNG.
dx, dy := 128, 128
if b.Dx() > b.Dy() {
dy = b.Dy() * dx / b.Dx()
} else {
dx = b.Dx() * dy / b.Dy()
}
i128 := resize.ResizeRGBA(i1, i1.Bounds(), dx, dy)


var buf bytes.Buffer
if err := png.Encode(&buf, i128); err != nil {
panic(err)
}


h := md5.New()
h.Write(buf.Bytes())
tag := fmt.Sprintf("%x", h.Sum(nil))[:32]


ctxt := fs.NewContext(req)
if err := ctxt.Write("qr/upload/"+tag+".png", buf.Bytes()); err != nil {
panic(err)
}


// Redirect with new image tag.
// Redirect to draw with new image tag.
http.Redirect(w, req, req.URL.Path+"?"+url.Values{"i": {tag}, "url": {link}}.Encode(), 302)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值