5

[Golang] Resize Image From Web

 2 years ago
source link: http://siongui.github.io/2017/01/13/go-resize-image-from-web/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Golang] Resize Image From Web

Updated: March 15, 2017

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

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

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:

[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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK