Golang : 如何读取 JPG(JPEG)、GIF 和 PNG 文件?
Go  /  管理员 发布于 1星期前   41
很难弄清楚为什么我所有打开和读取 JPG 或 JPEG 格式图像文件的尝试都会导致内存指针错误(当试图让 At() 和 Bounds() 函数工作时)。
在 Golang 中,必须先在 init() 部分注册格式,
然后才能尝试打开/读取图像文件并对文件执行操作。
下面的代码是关于如何打开和读取 JPEG/JPG 格式图像文件的简单指南:
package main
import (
"fmt"
"image"
"image/jpeg"
"os"
)
func init() {
// damn important or else At(), Bounds() functions will
// caused memory pointer error!!
image.RegisterFormat("jpeg", "jpeg", jpeg.Decode, jpeg.DecodeConfig)
}
func main() {
imgfile, err := os.Open("./img.jpg")
if err != nil {
fmt.Println("img.jpg file not found!")
os.Exit(1)
}
defer imgfile.Close()
img, _, err := image.Decode(imgfile)
fmt.Println(img.At(10, 10))
bounds := img.Bounds()
fmt.Println(bounds)
canvas := image.NewAlpha(bounds)
// is this image opaque
op := canvas.Opaque()
fmt.Println(op)
}
输出:
{255 128 128}
(0,0)-(760,479)
false
ps:
这也应该适用于 PNG 和 GIF 编码的图像。
博主 在
hyperf框架常用命令-在centos7中退出命令及在docker容器中退出命令中评论 @路过的靓仔:cdn静态资源被墙,已修复..GGGGGGGGG 在
layui框架常用输入框介绍中评论 写的很好解决问题..路过的靓仔 在
hyperf框架常用命令-在centos7中退出命令及在docker容器中退出命令中评论 剩下好多 wait 状态的..激光豆芽 在
为什么你不能安逸?国内996为什么没有国外955香?中评论 国内现在无意义的内卷太多了..激光豆芽 在
阿里云香港服务器搭建自用vpn:Shadowsocks使用流程步骤中评论 厉害了..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号