Last active
June 26, 2018 09:28
get & save picture size, width and height
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"flag" | |
"fmt" | |
_ "github.com/go-sql-driver/mysql" | |
"github.com/go-yaml/yaml" | |
"image" | |
_ "image/gif" | |
_ "image/jpeg" | |
_ "image/png" | |
"io/ioutil" | |
"os" | |
) | |
var db *sql.DB | |
var config *Configuration | |
var dir string | |
type Configuration struct { | |
Dir string `yaml:"dir"` | |
DSN string `yaml:"dsn"` | |
} | |
type Picture struct { | |
Id string | |
Hash string | |
MimeType string | |
Width int | |
Height int | |
Size int64 | |
} | |
func init() { | |
config = &Configuration{} | |
var configFile string | |
flag.StringVar(&configFile, "c", "settings.yaml", "config file name") | |
flag.Parse() | |
if ctx, err := ioutil.ReadFile(configFile); err != nil { | |
panic(err) | |
} else { | |
if err := yaml.Unmarshal(ctx, &config); err != nil { | |
panic(err) | |
} | |
} | |
} | |
func main() { | |
var err error | |
db, err = sql.Open("mysql", config.DSN) | |
if err != nil { | |
panic(err) | |
} | |
stmt, err := db.Prepare("SELECT picture_id, hash, mime_type FROM picture WHERE size=0 OR width=0 OR height=0") | |
if err != nil { | |
panic(err) | |
} | |
rows, err := stmt.Query() | |
if err != nil { | |
panic(err) | |
} | |
for rows.Next() { | |
picture := Picture{} | |
rows.Scan(&picture.Id, &picture.Hash, &picture.MimeType) | |
err := picture.Process() | |
if err != nil { | |
fmt.Println(err) | |
} else { | |
if _, err := db.Exec("UPDATE picture SET size=?, width=?, height=? WHERE picture_id=?", picture.Size, picture.Width, picture.Height, picture.Id); err != nil { | |
fmt.Println(err) | |
} | |
} | |
} | |
} | |
func (picture *Picture) Process() error { | |
path := config.Dir + fmt.Sprintf("/%s/%s/%s/%s/%s", picture.Hash[0:2], picture.Hash[2:4], picture.Hash[4:7], picture.Hash[7:10], picture.Hash[10:]) | |
switch picture.MimeType { | |
case "image/jpeg": | |
path += ".jpg" | |
case "image/png": | |
path += ".png" | |
case "image/gif": | |
path += ".gif" | |
} | |
file, err := os.Open(path) | |
if err != nil { | |
return err | |
} | |
fileInfo, err := file.Stat() | |
if err != nil { | |
return err | |
} | |
picture.Size = fileInfo.Size() | |
imageConfig, _, err := image.DecodeConfig(file) | |
if err != nil { | |
return err | |
} | |
picture.Height = imageConfig.Height | |
picture.Width = imageConfig.Width | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment