//image_resize.go
//如果是对gif进行缩放,需要对每帧缩放并对gif.Gif.Config中的尺寸进行缩放
package main
import (
"os"
"image"
_ "image/gif"
"log"
_ "image/png"
"image/jpeg"
"path/filepath"
"strings"
"regexp"
"time"
"math"
)
const vieux string="ori_image/"
func main(){
log.Println("处理当前文件夹的图片,并把旧文件放入ori_image")
_,err:=os.Stat(vieux)
if err!=nil{
log.Println(err)
os.MkdirAll(vieux,0666)//8进制 要有0
}
m,_:=filepath.Glob("*")
for _,name:=range m{//只列当前文件夹 不递归
if regexp.MustCompile( (`\.(jpe?g|png)$`)).MatchString(strings.ToLower( name)) {
resize(name)
}
}
}
func resize(name string) {
f,_:=os.Open(name)
defer f.Close()
img,ty,_:=image.Decode(f)
size:=img.Bounds().Dx()*img.Bounds().Dy()
scale:=math.Sqrt(float64(size/3e6)) //保留300万像素
scale=math.Max(1,scale) //较小的PNG 保存原大小 不放大
if ty!="jpeg"||scale>1.2{
log.Println("即将处理:",name)
var canvas image.Image
if scale==1{
canvas=img
}else{
w,h:=int(float64(img.Bounds().Dx())/scale),int(float64(img.Bounds().Dy())/scale)
canvas:=image.NewRGBA(image.Rect(0,0,w,h))
for row:=0;row<w;row++{
for col:=0;col<h;col++{
canvas.Set(row,col,img.At(int(float64(row)*scale),int(float64(col)*scale)))
}
}
}
f.Close()
output,_:=os.Create(time.Now().Format("20060102_150405_")+"缩放"+name[:len(name)-4]+".jpg")
jpeg.Encode(output,canvas,&jpeg.Options{70})
err:=os.Rename(name,filepath.Join(vieux,name))
echo_err(err)
return
}
}
func echo_err(err error){
if err!=nil{
log.Println(err)
panic(err)
}
}
对jpg与png的缩放压缩-go语言实现
最新推荐文章于 2023-07-01 20:14:55 发布