disintegration / imaging

Imaging is a simple image processing package for Go
MIT License
5.3k stars 443 forks source link

How to convert thumb directly to base64? #98

Closed mingguang615 closed 5 years ago

mingguang615 commented 5 years ago

package main

import ( "bufio" "encoding/base64" "fmt" "github.com/disintegration/imaging" "io/ioutil" "runtime" )

func main() {

// use all CPU cores for maximum performance
runtime.GOMAXPROCS(runtime.NumCPU())

img, err := imaging.Open("demo.jpg")
if err != nil {
    panic(err)
}

thumb := imaging.Thumbnail(img, 100, 100, imaging.CatmullRom)

// Read entire JPG into byte slice.
reader := bufio.NewReader(thumb)
content, _ := ioutil.ReadAll(reader)

// Encode as base64.
encoded := base64.StdEncoding.EncodeToString(content)

fmt.Println(encoded)

}

disintegration commented 5 years ago

Here's the example:

package main

import (
    "bytes"
    "encoding/base64"
    "fmt"
    "log"

    "github.com/disintegration/imaging"
)

func main() {
    img, err := imaging.Open("demo.jpg")
    if err != nil {
        log.Fatal(err)
    }

    thumb := imaging.Thumbnail(img, 100, 100, imaging.CatmullRom)

    var buf bytes.Buffer
    b64encoder := base64.NewEncoder(base64.StdEncoding, &buf)
    if err := imaging.Encode(b64encoder, thumb, imaging.JPEG); err != nil {
        log.Fatal(err)
    }
    if err := b64encoder.Close(); err != nil {
        log.Fatal(err)
    }
    encoded := buf.String()

    fmt.Println(encoded)
}

Note the line runtime.GOMAXPROCS(runtime.NumCPU()) isn't needed anymore, since Go version 1.5 (now it's the default behavior).

mingguang615 commented 5 years ago

Thanks very much!

------------------ 原始邮件 ------------------ 发件人: "Grigory Dryapak"notifications@github.com; 发送时间: 2019年6月29日(星期六) 晚上6:55 收件人: "disintegration/imaging"imaging@noreply.github.com; 抄送: "TCT"1758297909@qq.com; "Author"author@noreply.github.com; 主题: Re: [disintegration/imaging] How to convert thumb directly to base64?(#98)

Here's the example: package main import ( "bytes" "encoding/base64" "fmt" "log" "github.com/disintegration/imaging" ) func main() { img, err := imaging.Open("demo.jpg") if err != nil { log.Fatal(err) } thumb := imaging.Thumbnail(img, 100, 100, imaging.CatmullRom) var buf bytes.Buffer b64encoder := base64.NewEncoder(base64.StdEncoding, &buf) if err := imaging.Encode(b64encoder, thumb, imaging.JPEG); err != nil { log.Fatal(err) } if err := b64encoder.Close(); err != nil { log.Fatal(err) } encoded := buf.String() fmt.Println(encoded) }

Note the line runtime.GOMAXPROCS(runtime.NumCPU()) isn't needed anymore, since Go version 1.5 (now it's the default behavior).

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub, or mute the thread.