Repository: olahol/go-imageupload
Branch: master
Commit: 9b3f98f8b737
Files: 13
Total size: 8.9 KB
Directory structure:
gitextract_lsq4_nwm/
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── examples/
│ ├── save/
│ │ ├── index.html
│ │ └── main.go
│ ├── simple/
│ │ ├── index.html
│ │ └── main.go
│ └── thumbnailer/
│ ├── index.html
│ └── main.go
├── go.mod
├── go.sum
└── imageupload.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.DS_Store
*.swp
================================================
FILE: CHANGELOG.md
================================================
# 2022-09-14 (v1.0.0)
* Create Go module.
# 2016-05-03
* Add the PNG/JPEG thumbnail methods to *Image.
================================================
FILE: LICENSE
================================================
Copyright (c) 2022. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================
FILE: README.md
================================================
# go-imageupload
[](https://godoc.org/github.com/olahol/go-imageupload)
> :white_square_button: Gracefully handle image uploading and thumbnail creation.
## Install
```bash
go get github.com/olahol/go-imageupload
```
## [Example](https://github.com/olahol/go-imageupload/tree/master/examples)
Thumbnail creator.
```go
package main
import (
"net/http"
"github.com/olahol/go-imageupload"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.NotFound(w, r)
return
}
img, err := imageupload.Process(r, "file")
if err != nil {
panic(err)
}
thumb, err := imageupload.ThumbnailPNG(img, 300, 300)
if err != nil {
panic(err)
}
thumb.Write(w)
})
http.ListenAndServe(":5000", nil)
}
```
```html
```
## Contributors
* Ola Holmström (@olahol)
* Shintaro Kaneko (@kaneshin)
## [Documentation](https://godoc.org/github.com/olahol/go-imageupload)
================================================
FILE: examples/save/index.html
================================================
================================================
FILE: examples/save/main.go
================================================
package main
import (
"fmt"
"net/http"
"time"
"github.com/olahol/go-imageupload"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.NotFound(w, r)
return
}
img, err := imageupload.Process(r, "file")
if err != nil {
panic(err)
}
thumb, err := imageupload.ThumbnailPNG(img, 300, 300)
if err != nil {
panic(err)
}
thumb.Save(fmt.Sprintf("%d.png", time.Now().Unix()))
http.Redirect(w, r, "/", http.StatusMovedPermanently)
})
http.ListenAndServe(":5000", nil)
}
================================================
FILE: examples/simple/index.html
================================================
================================================
FILE: examples/simple/main.go
================================================
package main
import (
"net/http"
"github.com/olahol/go-imageupload"
)
var currentImage *imageupload.Image
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.HandleFunc("/image", func(w http.ResponseWriter, r *http.Request) {
if currentImage == nil {
http.NotFound(w, r)
return
}
currentImage.Write(w)
})
http.HandleFunc("/thumbnail", func(w http.ResponseWriter, r *http.Request) {
if currentImage == nil {
http.NotFound(w, r)
return
}
t, err := imageupload.ThumbnailJPEG(currentImage, 300, 300, 80)
if err != nil {
panic(err)
}
t.Write(w)
})
http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.NotFound(w, r)
return
}
img, err := imageupload.Process(r, "file")
if err != nil {
panic(err)
}
currentImage = img
http.Redirect(w, r, "/", http.StatusMovedPermanently)
})
http.ListenAndServe(":5000", nil)
}
================================================
FILE: examples/thumbnailer/index.html
================================================
================================================
FILE: examples/thumbnailer/main.go
================================================
package main
import (
"net/http"
"github.com/olahol/go-imageupload"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.NotFound(w, r)
return
}
img, err := imageupload.Process(r, "file")
if err != nil {
panic(err)
}
thumb, err := imageupload.ThumbnailPNG(img, 300, 300)
if err != nil {
panic(err)
}
thumb.Write(w)
})
http.ListenAndServe(":5000", nil)
}
================================================
FILE: go.mod
================================================
module github.com/olahol/go-imageupload
go 1.19
require github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
================================================
FILE: go.sum
================================================
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
================================================
FILE: imageupload.go
================================================
// Gracefully handle image uploading and thumbnail creation.
package imageupload
import (
"bytes"
"encoding/base64"
"errors"
"fmt"
"github.com/nfnt/resize"
"image"
_ "image/gif"
"image/jpeg"
"image/png"
"io/ioutil"
"net/http"
"strconv"
)
type Image struct {
Filename string
ContentType string
Data []byte
Size int
}
// Save image to file.
func (i *Image) Save(filename string) error {
return ioutil.WriteFile(filename, i.Data, 0600)
}
// Convert image to base64 data uri.
func (i *Image) DataURI() string {
return fmt.Sprintf("data:%s;base64,%s", i.ContentType, base64.StdEncoding.EncodeToString(i.Data))
}
// Write image to HTTP response.
func (i *Image) Write(w http.ResponseWriter) {
w.Header().Set("Content-Type", i.ContentType)
w.Header().Set("Content-Length", strconv.Itoa(i.Size))
w.Write(i.Data)
}
// Create JPEG thumbnail from image.
func (i *Image) ThumbnailJPEG(width int, height int, quality int) (*Image, error) {
return ThumbnailJPEG(i, width, height, quality)
}
// Create PNG thumbnail from image.
func (i *Image) ThumbnailPNG(width int, height int) (*Image, error) {
return ThumbnailPNG(i, width, height)
}
// Limit the size of uploaded files, put this before imageupload.Process.
func LimitFileSize(maxSize int64, w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxSize)
}
func okContentType(contentType string) bool {
return contentType == "image/png" || contentType == "image/jpeg" || contentType == "image/gif"
}
// Process uploaded file into an image.
func Process(r *http.Request, field string) (*Image, error) {
file, info, err := r.FormFile(field)
if err != nil {
return nil, err
}
contentType := info.Header.Get("Content-Type")
if !okContentType(contentType) {
return nil, errors.New(fmt.Sprintf("Wrong content type: %s", contentType))
}
bs, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
_, _, err = image.Decode(bytes.NewReader(bs))
if err != nil {
return nil, err
}
i := &Image{
Filename: info.Filename,
ContentType: contentType,
Data: bs,
Size: len(bs),
}
return i, nil
}
// Create JPEG thumbnail.
func ThumbnailJPEG(i *Image, width int, height int, quality int) (*Image, error) {
img, _, err := image.Decode(bytes.NewReader(i.Data))
thumbnail := resize.Thumbnail(uint(width), uint(height), img, resize.Lanczos3)
data := new(bytes.Buffer)
err = jpeg.Encode(data, thumbnail, &jpeg.Options{
Quality: quality,
})
if err != nil {
return nil, err
}
bs := data.Bytes()
t := &Image{
Filename: "thumbnail.jpg",
ContentType: "image/jpeg",
Data: bs,
Size: len(bs),
}
return t, nil
}
// Create PNG thumbnail.
func ThumbnailPNG(i *Image, width int, height int) (*Image, error) {
img, _, err := image.Decode(bytes.NewReader(i.Data))
thumbnail := resize.Thumbnail(uint(width), uint(height), img, resize.Lanczos3)
data := new(bytes.Buffer)
err = png.Encode(data, thumbnail)
if err != nil {
return nil, err
}
bs := data.Bytes()
t := &Image{
Filename: "thumbnail.png",
ContentType: "image/png",
Data: bs,
Size: len(bs),
}
return t, nil
}