• notice
  • Congratulations on the launch of the Sought Tech site

golang image processing library image basic operation example analysis

This article mainly introduces the relevant knowledge of golang image processing library image basic operation example analysis. The content is detailed and easy to understand, the operation is simple and fast, and has certain reference value. I believe that after reading this golang image processing library image basic operation example analysis article There are gains, let's take a look at it together.

Basic operation

Basic reading and saving of pictures.


Image reading is similar to file reading, you need to get the stream first:

  • The decoder of the registered image (eg: jpg import _ "image/jpeg", png import _ "image/png")

  • Get the stream by os.openopening a file;

  • Obtain the picture by image.Decodedecoding the stream;

func readPic () image . Image {
     f, err := os.Open( "C:\\hatAndSunglass.jpg" )
      if err != nil {
          panic (err)
     defer f.Close()

     img, fmtName, err := image.Decode(f)
     if err != nil {
          panic (err)
     fmt.Printf( "Name: %v, Bounds: %+v, Color: %+v" , fmtName, img.Bounds(), img.ColorModel())

     return img

The first parameter returned after decoding is the Image interface:

type Image interface {
   ColorModel() color.Model // returns the color model of the picture
   Bounds() Rectangle // returns the picture frame
   At(x, y int) color.Color // returns the color of the (x, y) pixel


Creating a new picture is very simple, just image.NewRGBAcreate a picture with a transparent background

img  :=  image.NewRGBA(image.Rect(0,  0 ,  300 ,  300 ))


Saving the picture is also very simple. After encoding, it can be written to the file stream:

  • Decoder for registered pictures

  • by os.createcreating a file; by

  • Over- png.Encodeencoded images and written to files;

func savePic (img *image.RGBA) {
     f, err := os.Create( "C:\\tmp.jpg" )
      if err != nil {
          panic (err)
     defer f.Close()
     b := bufio.NewWriter(f)
     err = jpeg.Encode(b, img, nil )
      if err != nil {
          panic (err)

image modification

Many operations require drawing pictures:

func Draw ( dst Image , r image .Rectangle , src image .Image , sp image .Point , op Op )
  func DrawMask ( dst Image , r image .Rectangle , src image .Image , sp image .Point , mask image .Image , mp image .Point , op Op )

Main parameter description:

  • dst: the background image of the drawing

  • r: the drawing area of the background image

  • src: the graph to draw

  • sp: the starting point to draw the graph src

  • op: Combination method

DrawMask has an additional mask mask parameter, which is a special form of Draw (mask related parameters are nil).


The read jpg image is not in RGBA format (in YCbCr format); the format needs to be converted before operation:

  • Create an RGBA image of the same size;

  • draw jpg onto the newly created image;

func jpg2RGBA( img image .Image ) * image .RGBA {
      tmp := image.NewRGBA(img.Bounds())

     draw.Draw (tmp, img.Bounds(), img, img.Bounds().Min , draw.Src)
     return tmp


The image can be easily cropped through the subImage method (it needs to be in RGBA format)

func subImg() {
      pic := readPic()
     fmt.Printf( " Type: %T\n" , pic)
     img := jpg2RCBA (pic)

     sub := img.SubImage (image.Rect( 0 , 0 , pic.Bounds().Dx(), pic.Bounds( ).Dy()/ 2 ))
      savePic (sub.(*image.RGBA))


Image scaling is divided into scaling that maintains the ratio and scaling that does not maintain the ratio; when maintaining the ratio, it is necessary to determine the position of the new image (whether it is centered), and how to fill in the blanks.
For scaling, new libraries need to be introduced golang.org/x/image/draw.

When maintaining the proportional scaling, you need to calculate the scaled image size first:

  • Calculate the scaling ratio of width and height respectively, whichever is smaller;

  • If it is centered (otherwise on the upper left), you need to calculate the padding size, and then calculate the position accordingly;

func calcResizedRect (width int , src image.Rectangle, height int , centerAlign bool ) image .Rectangle {
      var dst image.Rectangle
      if width* src.Dy () < height*src.Dx() { // width/src.width < height/src.height
         ratio := float64 (width) / float64 (src.Dx())

         tH := int ( float64 (src.Dy()) * ratio)
         pad := 0
         if centerAlign {
             pad = (height - tH) / 2
         dst = image.Rect( 0 , pad, width, pad+tH)
     } else {
         ratio := float64 (height) / float64 (src.Dy())
         tW := int ( float64 (src.Dx()) * ratio)
         pad := 0
         if centerAlign {
             pad = (width - tW) / 2
         dst = image.Rect(pad, 0 , pad+tW, height)

     return dst

After having the scaled size, the picture can be scaled by bilinear interpolation

  • img is the width of the image to be scaled, height is the scaled size

  • keepRatio is whether to keep the scaling

  • fill is the fill color (R, G, B are all fill)

  • centerAlign: Whether the image is stored in the center when the scale is maintained

import (


func resizePic (img image.Image, width int , height int , keepRatio bool , fill int , centerAlign bool ) image . Image {
     outImg := image.NewRGBA(image.Rect( 0 , 0 , width, height))
      if !keepRatio {
         draw.BiLinear.Scale(outImg, outImg.Bounds(), img, img.Bounds(), draw.Over, nil )
          return outImg

     if fill != 0 {
         fillColor := color.RGBA{R: uint8 (fill), G: uint8 (fill), B: uint8 (fill), A: 255 }
         draw.Draw(outImg, outImg.Bounds(), &image.Uniform{C: fillColor}, image.Point{}, draw.Src)
     dst := calcResizedRect(width, img.Bounds(), height, centerAlign)
     draw.ApproxBiLinear.Scale(outImg, dst.Bounds(), img, img.Bounds(), draw.Over, nil )
      return outImg

The content of the article "Example Analysis of Basic Image Operation of Golang Image Processing Library" is introduced here, thank you for reading! I believe that everyone has a certain understanding of the knowledge of "basic operation example analysis of golang image processing library image". 


Technical otaku

Sought technology together

Related Topic


Leave a Reply