[Golang] Resize Image From Web


This post gives an example that read an png image from website (use Google log as example) and resize it in half.

Install the image resizing library (github.com/nfnt/resize) first:

$ go get github.com/nfnt/resize

The full example:

web.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package resize

import (
	"github.com/nfnt/resize"
	"image/png"
	"io"
	"os"
)

func ResizePng(r io.Reader, filepath string) {
	// decode png into image.Image
	img, err := png.Decode(r)
	if err != nil {
		panic(err)
	}

	// resize to width 60 using Lanczos resampling
	// and preserve aspect ratio
	m := resize.Resize(60, 0, img, resize.Lanczos3)

	out, err := os.Create(filepath)
	if err != nil {
		panic(err)
	}
	defer out.Close()

	// write new image to file
	png.Encode(out, m)
}
web_test.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package resize

import (
	"net/http"
	"testing"
)

func TestResizePng(t *testing.T) {
	// open image on web
	resp, err := http.Get("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png")
	if err != nil {
		t.Error(err)
		return
	}
	defer resp.Body.Close()

	ResizePng(resp.Body, "test_resized.png")
}

For more usage of github.com/nfnt/resize, visit its GitHub page. If your image is of JPEG format, import image/jpeg and modify the code correspondingly.


Source code tested on: Ubuntu Linux 16.10, Go 1.8.


References:

[1]
[2]
[3]Go Resizing Images - Stack Overflow
[4]GitHub - fawick/speedtest-resize: Compare various Image resize algorithms for the Go language
[5]Guess Metadata from HTML and Converted to reStructuredText
[6]Creative coding in Go : golang
[7]Small microservice to crop images on-the-fly : golang
[8]Building a Cloudinary clone microservice. Would Go be a good choice? : golang