網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
go實(shí)現(xiàn)圖片拼接與文字書(shū)寫(xiě)的方法實(shí)例_Golang
作者:Yasin_Copeleft ? 更新時(shí)間: 2022-04-08 編程語(yǔ)言零:背景
這是我工作中實(shí)際碰到的后端生成圖片拼接和文字貼圖需求。特此總結(jié)下來(lái),方便后人。文中代碼都是我們生產(chǎn)環(huán)境使用的。
一:圖片拼接
go標(biāo)準(zhǔn)庫(kù)的image包本身就能實(shí)現(xiàn)拼接,因此還是比較簡(jiǎn)單的
直接上代碼
1.1 圖片拼接代碼
//圖片拼接 func MergeImageNew(base image.Image, mask image.Image, paddingX int, paddingY int) (*image.RGBA, error) { baseSrcBounds := base.Bounds().Max maskSrcBounds := mask.Bounds().Max newWidth := baseSrcBounds.X newHeight := baseSrcBounds.Y maskWidth := maskSrcBounds.X maskHeight := maskSrcBounds.Y des := image.NewRGBA(image.Rect(0, 0, newWidth, newHeight)) // 底板 //首先將一個(gè)圖片信息存入jpg draw.Draw(des, des.Bounds(), base, base.Bounds().Min, draw.Over) //將另外一張圖片信息存入jpg draw.Draw(des, image.Rect(paddingX, newHeight-paddingY-maskHeight, (paddingX+maskWidth), (newHeight-paddingY)), mask, image.ZP, draw.Over) return des, nil }
核心就是使用image>newRGBA新建一個(gè)空白底圖,讓后將背景圖,拼接圖使用draw.Draw畫(huà)上去就好了。
1.2 從本地、網(wǎng)絡(luò)讀取圖片
從本地讀取
func GetImageFromFile(filePath string) (img image.Image, err error) { f1Src, err := os.Open(filePath) if err != nil { return nil, err } defer f1Src.Close() buff := make([]byte, 512) // why 512 bytes ? see http://golang.org/pkg/net/http/#DetectContentType _, err = f1Src.Read(buff) if err != nil { return nil, err } filetype := http.DetectContentType(buff) fmt.Println(filetype) fSrc, err := os.Open(filePath) defer fSrc.Close() switch filetype { case "image/jpeg", "image/jpg": img, err = jpeg.Decode(fSrc) if err != nil { fmt.Println("jpeg error") return nil, err } case "image/gif": img, err = gif.Decode(fSrc) if err != nil { return nil, err } case "image/png": img, err = png.Decode(fSrc) if err != nil { return nil, err } default: return nil, err } return img, nil }
從網(wǎng)絡(luò)中讀取
func GetImageFromNet(url string) (image.Image, error) { res, err := http.Get(url) if err != nil || res.StatusCode != 200 { return nil, err } defer res.Body.Close() m, _, err := image.Decode(res.Body) return m, err }
保存圖片
func SaveImage(targetPath string, m image.Image) error { fSave, err := os.Create(targetPath) if err != nil { return err } defer fSave.Close() err = jpeg.Encode(fSave, m, nil) if err != nil { return err } return nil }
二:文字書(shū)寫(xiě)
圖片書(shū)寫(xiě)文字是基于 github.com/golang/freetype 這個(gè)庫(kù)實(shí)現(xiàn)的
import ( "github.com/golang/freetype" "github.com/golang/freetype/truetype" "golang.org/x/image/font" "image" "io/ioutil" ) //字體相關(guān) type TextBrush struct { FontType *truetype.Font FontSize float64 FontColor *image.Uniform TextWidth int } func NewTextBrush(FontFilePath string, FontSize float64, FontColor *image.Uniform, textWidth int) (*TextBrush, error) { fontFile, err := ioutil.ReadFile(FontFilePath) if err != nil { return nil, err } fontType, err := truetype.Parse(fontFile) if err != nil { return nil, err } if textWidth <= 0 { textWidth = 20 } return &TextBrush{FontType: fontType, FontSize: FontSize, FontColor: FontColor, TextWidth: textWidth}, nil } // 圖片插入文字 func (fb *TextBrush) DrawFontOnRGBA(rgba *image.RGBA, pt image.Point, content string) { c := freetype.NewContext() c.SetDPI(72) c.SetFont(fb.FontType) c.SetHinting(font.HintingFull) c.SetFontSize(fb.FontSize) c.SetClip(rgba.Bounds()) c.SetDst(rgba) c.SetSrc(fb.FontColor) c.DrawString(content, freetype.Pt(pt.X, pt.Y)) } func Image2RGBA(img image.Image) *image.RGBA { baseSrcBounds := img.Bounds().Max newWidth := baseSrcBounds.X newHeight := baseSrcBounds.Y des := image.NewRGBA(image.Rect(0, 0, newWidth, newHeight)) // 底板 //首先將一個(gè)圖片信息存入jpg draw.Draw(des, des.Bounds(), img, img.Bounds().Min, draw.Over) return des }
使用example
func TestTextBrush_DrawFontOnRGBA(t *testing.T) { textBrush, err := NewTextBrush("字體庫(kù)ttf位置", 20, image.Black, 20) if err != nil { t.Log(err) } backgroud, err := GetImageFromFile("./resource/backgroud.jpg") if err != nil { t.Log(err) } des := Image2RGBA(backgroud) textBrush.DrawFontOnRGBA(des, image.Pt(10, 50), "世界你好") //調(diào)整顏色 textBrush.FontColor = image.NewUniform(color.RGBA{ R: 0x8E, G: 0xE5, B: 0xEE, A: 255, }) textBrush.DrawFontOnRGBA(des, image.Pt(10, 80), "我是用Go拼上的文字") if err := SaveImage("./resource/text.png", des); err != nil { t.Log(err) } }
先使用NewTextBrush第一個(gè)參數(shù)是字體庫(kù)文件位置。這里使用的ttf格式的字體庫(kù),網(wǎng)上應(yīng)該有免費(fèi)的字體庫(kù)。
參考我的example中的代碼就可以直接使用。
總結(jié)
原文鏈接:https://juejin.cn/post/7056679847585808392
相關(guān)推薦
- 2022-07-04 C#操作配置文件app.config、web.config增刪改_C#教程
- 2022-09-15 C#?List的賦值問(wèn)題的解決_C#教程
- 2023-03-19 Python學(xué)習(xí)之configparser模塊的使用詳解_python
- 2022-06-22 Android使用EventBus多次接收消息_Android
- 2022-09-24 win2019?ftp服務(wù)器搭建圖文教程_FTP服務(wù)器
- 2022-07-30 C++深入分析講解函數(shù)與重載知識(shí)點(diǎn)_C 語(yǔ)言
- 2022-11-06 Android實(shí)現(xiàn)圓形圖片小工具_(dá)Android
- 2022-05-23 Docker容器鏡像相關(guān)命令基本介紹與使用_docker
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支