This article mainly introduces:
- Reading and writing of picture files.
- How do images convert to and from base64 in the go cache
- Picture clipping
In this article, all wrong judgments are removed for easy viewing
base64 -> file ddd, _ := base64.StdEncoding. DecodeString (datasource)//Generate an image file and write the file to the buffer Err2:=ioutil. WriteFile ("./output. jpg", ddd, 0666)//buffer is output to the jpg file (write to the file directly without processing) datasource base64 string base64 -> buffer ddd, _ := base64.StdEncoding. DecodeString (datasource)//Generate an image file and write the file to the buffer bbb := bytes. NewBuffer (ddd)//A buffer must be added, or an error will be reported without the read method After being converted into a buffer, there will be a Reader method. Can be decoded by the image API Buffer ->ImageBuff m, _, _ := image. Decode (bbb)//Image file decoding rgbImg := m.(*image.YCbCr) SubImg:=rgbImg. SubImage (image. Rect (0, 0, 200, 200)). (* image. YCbCr)//Image clipping x0 y0 x1 y1 Img ->file (code continues above) f, _ := Os. Create ("test. jpg")//Create a file Defer f. Close()//Close the file jpeg. Encode (f, subImg, nil)//Write the file Img ->base64 (code continues above) Copy Code emptyBuff := bytes. NewBuffer (nil)//Create a new empty buffer jpeg. Encode (emptyBuff, subImg, nil)//img writes to buff Dist:=make ( byte, 50000)//Create storage space base64.StdEncoding. Encode (dist, emptyBuff. Bytes())//convert buff to base64 fmt. Println (string (dist))//Output picture base64 (type= byte) _ = Ioutil. WriteFile ("./base64pic. txt", dist, 0666)//The buffer is output to the jpg file (write to the file directly without processing) Copy Code imgFile -> base64 ff, _ := Ioutil. ReadFile ("output2. jpg")//I prefer to use this to read files quickly Bufstore:=make ( byte, 5000000)//Data cache base64.StdEncoding. Encode (bufstore, ff)//Convert the file to base64 _ = Ioutil. WriteFile ("./output2. jpg. txt", dist, 0666)//Write directly to the file and it will be finished.