寻找更好的方法将内存映像保存到文件

The goal of the code is to download an image, stick it to a larger parent image and save the result.

After quite a few failures I ended up with the following code that does work.

However, is there a better way than using bytes.Buffer and a writer to save the target image to a file / pass it to an httpResponse?

package main

import (
    "image"
    "image/draw"
    "image/jpeg"
    "os"
    // "image/color"
    // "io/ioutil"
    // "fmt"
    "bufio"
    "bytes"
    "log"
    "net/http"
)

func main() {
    // Fetch an image.
    resp, err := http.Get("http://katiebrookekennels.com/wp-content/uploads/2014/10/dog-bone4.jpg")
    if err != nil {
        log.Panic(err)
    }
    defer resp.Body.Close()

    // Keep an in memory copy.
    myImage, err := jpeg.Decode(resp.Body)

    if err != nil {
        log.Panic(err)
    }

    // Prepare parent image where we want to position child image.
    target := image.NewRGBA(image.Rect(0, 0, 800, 800))
    // Draw white layer.
    draw.Draw(target, target.Bounds(), image.White, image.ZP, draw.Src)
    // Draw child image.
    draw.Draw(target, myImage.Bounds(), myImage, image.Point{0, 0}, draw.Src)

    // Encode to jpeg.
    var imageBuf bytes.Buffer
    err = jpeg.Encode(&imageBuf, target, nil)

    if err != nil {
        log.Panic(err)
    }

    // Write to file.
    fo, err := os.Create("img.jpg")
    if err != nil {
        panic(err)
    }
    fw := bufio.NewWriter(fo)

    fw.Write(imageBuf.Bytes())
}
查看全部
dongpang4470
dongpang4470
2016/10/07 23:42
  • image
  • io
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复