SHARE
TWEET

Untitled

a guest Jun 15th, 2019 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "bytes"
  5.     "fmt"
  6.     "image"
  7.     "image/color"
  8.     "image/draw"
  9.     "image/jpeg"
  10.     "io/ioutil"
  11.     "log"
  12.     "os"
  13. )
  14.  
  15. func main() {
  16.     f, err := os.Open("resources/image.jpg")
  17.     if err != nil {
  18.         log.Fatal(err)
  19.     }
  20.  
  21.     img, str, err := image.Decode(f)
  22.     if err != nil {
  23.         log.Fatal(err)
  24.     }
  25.     fmt.Println(str)
  26.  
  27.     resImg := resize(img, 3)
  28.     fmt.Println(resImg)
  29.  
  30.     imgBytes := imgToBytes(resImg)
  31.     fmt.Println(imgBytes)
  32.  
  33.     err = ioutil.WriteFile("resources/test.jpg", imgBytes, 0777)
  34.     if err != nil {
  35.         log.Fatal(err)
  36.     }
  37. }
  38.  
  39. func resize(img image.Image, scale int) image.Image {
  40.     imgRect := image.Rect(img.Bounds().Min.X/scale, img.Bounds().Min.Y/scale, img.Bounds().Max.X/scale, img.Bounds().Max.Y/scale)
  41.     resImg := image.NewRGBA(imgRect)
  42.     draw.Draw(resImg, resImg.Bounds(), &image.Uniform{C: color.White}, image.ZP, draw.Src)
  43.     for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y += scale {
  44.         for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x += scale {
  45.             resImg.Set(x/scale, y/scale, img.At(x, y))
  46.         }
  47.     }
  48.  
  49.     return resImg
  50. }
  51.  
  52. func imgToBytes(img image.Image) []byte {
  53.     var opt jpeg.Options
  54.     opt.Quality = 80
  55.  
  56.     buff := bytes.NewBuffer(nil)
  57.     err := jpeg.Encode(buff, img, &opt) // put quality to 80%
  58.     if err != nil {
  59.         log.Fatal(err)
  60.     }
  61.  
  62.     return buff.Bytes()
  63. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top