当前位置:网站首页>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
}
边栏推荐
- 智能合约安全——私有数据访问
- 那些破釜沉舟入局Web3.0的互联网精英都怎么样了?
- The use and principle of distributed current limiting reduction RRateLimiter
- 微服务该如何拆分?
- Huawei issues another summoning order for "Genius Boys"!He, who had given up an annual salary of 3.6 million, also made his debut
- 【回归预测-lssvm分类】基于最小二乘支持向量机lssvm实现数据分类代码
- canal scrape data
- Use of SLF4J
- 有关收集箱的改进建议
- 剑指 Offer II 037. 小行星碰撞
猜你喜欢

Mysql数据库查询好慢,除了索引,还能因为什么?

【云原生 • DevOps】influxDB、cAdvisor、Grafana 工具使用详解

关于mariadb/mysql的user表:密码正确但登录失败,可能与mysql的空用户有关

Memory-mapped, bit-band operations

泡沫褪去,DeFi还剩下什么

国内数字藏品的乱象与未来

JUC常见的线程池源码学习 02 ( ThreadPoolExecutor 线程池 )

【回归预测-CNN预测】基于卷积神经网络CNN实现数据回归预测附matlab代码

Kubernetes应用管理深度剖析

(Crypto essential dry goods) Detailed analysis of the current NFT trading markets
随机推荐
Office Automation | Office Software and Edraw MindMaster Shortcuts
[机缘参悟-53]:《素书》-3-修身养志[求人之志章第三]
Smart Contract Security - Private Data Access
CS内网横向移动 模拟渗透实操 超详细
HUAWEI CLOUD Releases Open Source Software Governance Service - Software Component Analysis
websocket flv 客户端解封包
ISELED---氛围灯方案的新选择
Huawei issues another summoning order for "Genius Boys"!He, who had given up an annual salary of 3.6 million, also made his debut
(Crypto essential dry goods) Detailed analysis of the current NFT trading markets
Web3创始人和建设者必备指南:如何构建适合的社区?
The evolution of content products has three axes: traffic, technology, and product form
华为无线设备Mesh配置命令
JUC common thread pool source learning 02 ( ThreadPoolExecutor thread pool )
CVE-2022-33891 Apache Spark 命令注入复现
MySql error: SqlError(Unable to execute query", "Can't create/write to file OS errno 2 - No such file...
算力顶天地,存力纳乾坤:国家超级计算济南中心的一体两面
【回归预测-lssvm分类】基于最小二乘支持向量机lssvm实现数据分类代码
有关收集箱的改进建议
This editor actually claims to be as fast as lightning!
瑞吉外卖项目实战Day02