Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
getimagedimensions.go
package main
import (
"database/sql"
"flag"
"image"
_ "image/jpeg"
_ "image/png"
"io/ioutil"
"log"
"os"
"path/filepath"
"github.com/m-butterfield/mattbutterfield.com/datastore"
"github.com/m-butterfield/mattbutterfield.com/website"
)
const (
concurrency = 10
updateDimensionsStatement = "UPDATE images SET width = ?, height = ? WHERE id = ?"
)
var (
imageStore datastore.DBImageStore
logger = &log.Logger{}
)
func main() {
logger.SetOutput(os.Stdout)
db, err := datastore.InitDB(website.DBFileName)
imageStore = datastore.DBImageStore{DB: db}
dir := flag.String("d", "", "directory path")
flag.Parse()
files, err := ioutil.ReadDir(*dir)
if err != nil {
panic(err)
}
sem := make(chan bool, concurrency)
for _, file := range files {
sem <- true
getDimensions(filepath.Join(*dir, file.Name()), sem)
}
for i := 0; i < cap(sem); i++ {
sem <- true
}
}
func getDimensions(fileName string, sem chan bool) {
defer func() { <-sem }()
file, err := os.Open(fileName)
defer file.Close()
if err != nil {
panic(err)
}
img, _, err := image.DecodeConfig(file)
if err != nil {
panic(err)
}
logger.Printf("Image: %s\tw:%d\th:%d", fileName, img.Width, img.Height)
storeDimensions(filepath.Base(fileName), img.Width, img.Height)
}
func storeDimensions(imageID string, width, height int) {
_, err := imageStore.GetImage(imageID)
if err == sql.ErrNoRows {
logger.Printf("Img: %s not found...", imageID)
return
} else if err != nil {
panic(err)
}
logger.Println("Updating width and height...")
_, err = imageStore.DB.Exec(updateDimensionsStatement, width, height, imageID)
if err != nil {
panic(err)
}
}
var thing = `
BEGIN TRANSACTION;
ALTER TABLE images RENAME TO temp_images;
CREATE TABLE images (
id TEXT PRIMARY KEY,
caption TEXT,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
location TEXT,
width INTEGER NOT NULL,
height INTEGER NOT NULL
);
INSERT INTO images
SELECT
id, caption, created_at, location, width, height
FROM
temp_images;
DROP TABLE temp_images;
COMMIT;
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment