当前位置:网站首页>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
}
边栏推荐
猜你喜欢
随机推荐
【回归预测-lssvm分类】基于最小二乘支持向量机lssvm实现数据分类代码
MongoDB启动报错 Process: 29784 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=14)
localhost with 127.0.0.1
B+树索引页大小是如何确定的?
从实例来看DAO:权力分散的伟大尝试
Lock wait timeout exceeded解决方案
华为无线设备Mesh配置命令
GeoServer
惊艳!京东T8纯手码的Redis核心原理手册,基础与源码齐下
JVM performance tuning
组态 - 笔记
TensorFlow自定义训练函数
5G-based Warehousing Informatization Solution 2022
Redis cache penetration, breakdown, avalanche and consistency issues
DDS Arbitrary Waveform Output Based on FPGA
关于mariadb/mysql的user表:密码正确但登录失败,可能与mysql的空用户有关
Flink本地UI运行
Mysql数据库查询好慢,除了索引,还能因为什么?
Huawei issues another summoning order for "Genius Boys"!He, who had given up an annual salary of 3.6 million, also made his debut
Normal and escaped strings for postgresql








