利用Go語言上傳映像並產生縮圖

來源:互聯網
上載者:User

承前文: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)
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.