当前位置:网站首页>Introduction to golang image processing library image
Introduction to golang image processing library image
2022-07-30 15:32:00 【alwaysrun】
goStandard library for processing images in image支持常见的PNG、JPEG、GIFimage processing in other formats(可读取、裁剪、绘制、生成等).
基本操作
Basic reading and saving of pictures.
读取
Image reading is similar to file reading,The stream needs to be fetched first:
- Register the decoder for the picture(如:jpg则
import _ "image/jpeg", png则import _ "image/png") - 通过
os.openOpen a file to get the stream; - 通过
image.Decode解码流,获取图片;
import _ "image/jpeg"
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 Image接口:
type Image interface {
ColorModel() color.Model // Returns the color model of the image
Bounds() Rectangle // Returns the picture frame
At(x, y int) color.Color // 返回(x,y)像素点的颜色
}
新建
Creating a new image is very simple,只需image.NewRGBAYou can create a picture with a transparent background
img := image.NewRGBA(image.Rect(0, 0, 300, 300))
保存
Saving pictures is also simple,After encoding is required,Write to a file stream:
- Register the decoder for the picture
- 通过
os.create创建文件; - 通过
png.EncodeEncode the picture and write it to a file;
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)
}
b.Flush()
}
图片修改
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)
主要参数说明:
- dst:Drawing background image
- r:The drawing area for the background image
- src:要绘制的图
- sp:to draw the diagramsrc的开始点
- op:组合方式
DrawMaskOne more mask mask parameter,Drawa special form of it(The mask related parameters are nil).
转换
读取的jpg图像不是RGBA格式的(为YCbCr格式);The format needs to be converted before operation:
- Create one of the same sizeRGBA图像;
- 把jpgDraw 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
}
裁剪
通过subImageThe method can easily crop the picture(需要为RGBA格式的)
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;while maintaining the proportions,To determine the location of the new image(是否居中),and how to fill in the blanks.
为了缩放,需要引入新的库golang.org/x/image/draw.
while maintaining scaling,The scaled image size needs to be calculated first:
- Calculate the width separately、高的缩放比例,Whichever is smaller;
- If centered(Otherwise, go to the upper left)The padding size needs to be calculated,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,You can use bilinear interpolationbilinearway to zoom the image
- imgfor the image to be scaled
- width、heightis the scaled size
- keepRatioWhether to maintain proportional scaling
- fill为填充的颜色(R、G、B都为fill)
- centerAlign:While maintaining scaling,Whether the image is centered
import (
"image"
"image/color"
"golang.org/x/image/draw"
)
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
}
边栏推荐
猜你喜欢
随机推荐
GeoServer + openlayers
延时消息队列
1222. 可以攻击国王的皇后-力扣双百代码
GeoServer
定时任务 corn
How is the B+ tree index page size determined?
InputStream和OutputStream流的使用
JVM performance tuning
Flink real-time data warehouse completed
Sentinel
微服务架构下的核心话题 (二):微服务架构的设计原则和核心话题
Flink本地UI运行
952. 按公因数计算最大组件大小 : 枚举质因数 + 并查集运用题
Android jump to google app market
(Crypto essential dry goods) Detailed analysis of the current NFT trading markets
基于FPGA的DDS任意波形输出
canal抓取数据
postgresql的普通字符串和转义字符串
Office Automation | Office Software and Edraw MindMaster Shortcuts
Excel使用Visual Basic Editor对宏进行修改









