当前位置:网站首页>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
}
边栏推荐
猜你喜欢

2022最新 | 室外单目深度估计研究综述

嵌入式开发:嵌入式基础知识——正确启动固件项目的 10 条建议

Metaverse Post Office AI space-themed series of digital collections will be launched at 10:00 on July 30th "Yuanyou Digital Collection"

5G-based Warehousing Informatization Solution 2022

Installing and Uninstalling MySQL on Mac

使用 protobuf 进行数据序列化

Memory-mapped, bit-band operations

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

GeoServer + openlayers

MongoDB starts an error Process: 29784 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=14)
随机推荐
华为无线设备Mesh配置命令
华为再发「天才少年」召集令!曾放弃360万年薪的他也来首秀
[Cloud native] Alibaba Cloud ARMS business real-time monitoring
视频加密的误解
B+树索引页大小是如何确定的?
Could not acquire management access for administration
ESP32 Repeated Reboot Issue Arduino Shield Power Outage Detector
机房布线的至高境界,美到窒息
微服务架构下的核心话题 (二):微服务架构的设计原则和核心话题
HUAWEI CLOUD Releases Open Source Software Governance Service - Software Component Analysis
Use of SLF4J
浅析显卡市场的未来走向:现在可以抄底了吗?
DDS Arbitrary Waveform Output Based on FPGA
组态 - 笔记
泡沫褪去,DeFi还剩下什么
SQL 优化这么做就对了!
微服务该如何拆分?
Extremely Knowing v2 Analysis
如何做好技术选型
Allure Advanced - Dynamically Generate Report Content