func main() { if len(os.Args) != 3 { log.Print("Please supply an input and output filename e.g. ./examples foo.jpg bar.jpg") os.Exit(1) } input := os.Args[1] output := os.Args[2] log.Printf("Reading from file %s, writing to file %s", input, output) for i := 0; i < 10; i++ { start := time.Now() image, err := magick.NewFromFile(input) log.Printf("Loading image took %v\n", time.Now().Sub(start)) if err != nil { log.Printf("Error reading from file %s", err.Error()) os.Exit(1) } log.Print("Transforming") err = image.Resize("400x200") if err != nil { log.Print("Problem with transforming") os.Exit(1) } err = image.Shadow("#F00", 255, 5, 2, 2) if err != nil { log.Print("Problem with transforming") os.Exit(1) } err = image.FillBackgroundColor("#00F") if err != nil { log.Print("Problem setting background") os.Exit(1) } log.Printf("Writing to %s", output) err = image.ToFile(output) if err != nil { log.Printf("Error outputing file: %s", err.Error()) os.Exit(1) } log.Printf("Wrote to %s %b", output) end := time.Now() log.Printf("Done. took %v\n", time.Now().Sub(start)) image.Destroy() } }
func (thumb Thumb) Generate() (*magick.MagickImage, error) { if g := thumb.Geometry.String(); !IsValidGeometry(g) { return nil, ErrorGeometryNotAllowed{g} } sourcePath := thumb.MainFullPath() log("Generating from %s", sourcePath) image, err := magick.NewFromFile(sourcePath) if err != nil { return image, err } err = image.Resize(thumb.Geometry.String()) return image, err }
func isQualified(filePath string, imageCaches *ImageMetaCaches) bool { if cache, exist := (*imageCaches)[filePath]; exist { return isOk(cache.Type, cache.Width, cache.Height) } image, err := magick.NewFromFile(filePath) if err != nil { return false } defer image.Destroy() result := isOk(image.Type(), image.Width(), image.Height()) phash, err := phash.ImageHashDCT(filePath) (*imageCaches)[filePath] = ImageMetaCache{ filePath, image.Width(), image.Height(), image.Type(), phash, } return result }
func (ws WebServer) handler(w http.ResponseWriter, r *http.Request) { var currentSessionCookie *http.Cookie var error error var html []byte //respons data array //check cookie for auth currentSessionCookie, error = r.Cookie("gypoSession") //if /login requests if r.URL.Path[1:] == "login" { //respons packet var newPacket packet.PacketStd //if no cookie, authentiate if error != nil { newWebSession := session.WebSession{} newWebSession.User = user.User{-1} newWebSession.RootDir = ws.RootDir newWebSession.SessionChan = ws.SessionsChan var loginCode int var loginCodeStr string //authenticates form input loginCode = newWebSession.WebSession_Authenticate(r.FormValue("username"), r.FormValue("password")) loginCodeStr = strconv.Itoa(loginCode) //makes respons packets from loginCode return value if loginCode < 0 { //not success newPacket = packet.PacketStd{packet.Packet{"text", "loginCode"}, loginCodeStr} } else { //succes newPacket = packet.PacketStd{packet.Packet{"text", "loginCode"}, loginCodeStr} newWebSession.User.Id = loginCode //sets client cookie newSessionCookie := &http.Cookie{Name: "gypoSession", Value: strconv.Itoa(newWebSession.User.Id), Domain: ".localhost.com", Expires: time.Now().AddDate(0, 0, 1)} //expires in 24h - time.Now().Add(120*60*1000) http.SetCookie(w, newSessionCookie) } //if cookie, prolong expiration } else { newSessionCookie := &http.Cookie{Name: "gypoSession", Value: currentSessionCookie.Value, Domain: ".localhost.com", Expires: time.Now().AddDate(0, 0, 1)} //expires in 24h - time.Now().Add(120*60*1000) http.SetCookie(w, newSessionCookie) } //writes response packets to client with json html, _ = json.Marshal(newPacket) w.Header().Set("Content-Type", "application/json") //everything but /login } else { //if currentSessionCookie missing, no auth if error != nil { if r.URL.Path == "/" || r.URL.Path == "" || r.URL.Path == "/favicon.ico" { //Browsers automatically request the favicon.ico file by default when you issue a request for a web page. The favicon.ico file is the small icon that appears in the URL bar of your browser. //trys to load login for client html, error = ws.loadPage("index") if error != nil { html = []byte("could not load index") } } else { html = []byte("you need to login first") } } else { //refreshes cookie newSessionCookie := &http.Cookie{Name: "gypoSession", Value: currentSessionCookie.Value, Domain: ".localhost.com", Expires: time.Now().AddDate(0, 0, 1)} //expires in 24h - time.Now().Add(120*60*1000) http.SetCookie(w, newSessionCookie) userId, _ := strconv.Atoi(currentSessionCookie.Value) //redirects to overview as auth is ok if r.URL.Path == "/" || r.URL.Path == "" || r.URL.Path == "/favicon.ico" { //trys to load login for client html, error = ws.loadPage("overview") if error != nil { html = []byte("could not load overview") } //overview jason } else if r.URL.Path[1:] == "getOverview" { db, error := sql.Open("sqlite3", ws.RootDir+"/gypo.db") if error != nil { html = []byte(error.Error()) } else { //get number of files to populate fileList array var dbFileCount int error = db.QueryRow("SELECT count(*) AS number FROM files WHERE user_id = ?", userId).Scan(&dbFileCount) if error != nil { html = []byte(error.Error()) } else { rows, error := db.Query("SELECT id, filename, path, is_dir FROM files WHERE user_id = ? ", userId) if error != nil { html = []byte(error.Error()) } else { var id int var filename, path string var is_dir bool var fileList packet.PacketList var file packet.PacketStd //set array size fileList.ContentType = "json" fileList.Name = "fileList" fileList.Data = make([]packet.PacketStd, dbFileCount) //populate array with file objects i := 0 for rows.Next() { error = rows.Scan(&id, &filename, &path, &is_dir) if error != nil { file = packet.PacketStd{packet.Packet{"file", "error"}, error.Error()} } else { if is_dir == true { file = packet.PacketStd{packet.Packet{"folder", path}, strconv.Itoa(id)} } else { mimeStr := mime.TypeByExtension(strings.ToLower(filename[strings.LastIndex(filename, "."):])) //to lower case to ensure equal parse file = packet.PacketStd{packet.Packet{"file|" + mimeStr, path + "|" + filename}, strconv.Itoa(id)} } } fileList.Data[i] = file i++ } //marshals fileList to json and sets proper content-type header html, _ = json.Marshal(fileList) w.Header().Set("Content-Type", "application/json") } db.Close() } } } else if strings.Index(r.URL.Path, "getFile") == 1 { db, error := sql.Open("sqlite3", ws.RootDir+"/gypo.db") defer db.Close() if error != nil { html = []byte(error.Error()) } else { var path, filename string fileId, _ := strconv.Atoi(r.URL.RawQuery[strings.Index(r.URL.RawQuery, "=")+1:]) error = db.QueryRow("SELECT path, filename number FROM files WHERE id = ?", fileId).Scan(&path, &filename) if error != nil { html = []byte(error.Error()) } else { pathfile := ws.RootDir + "/user-" + strconv.Itoa(userId) + path + filename file, error := os.Open(pathfile) if error != nil { html = []byte(error.Error()) } else { defer file.Close() //get filesize fi, _ := file.Stat() fileSize := int(fi.Size()) //reads file and writes it to buffer array html = make([]byte, fileSize) bytesWritten := 0 i := 0 fmt.Println("File to be written: " + fi.Name() + " | size: " + strconv.Itoa(fileSize)) //set headers accoring to file mimeStr := mime.TypeByExtension(filename[strings.LastIndex(filename, "."):]) fmt.Println("setting content-type: " + mimeStr) w.Header().Set("Content-Type", mimeStr) w.Header().Set("Content-Length", strconv.Itoa(fileSize)) w.Header().Set("Content-Disposition", "attachment; filename="+filename) for bytesWritten < fileSize && error == nil { i, error = file.Read(html[bytesWritten:]) if error != nil { html = []byte(error.Error()) } else { bytesWritten = bytesWritten + i } } } } } } else if strings.Index(r.URL.Path, "getImage") == 1 { fmt.Println("getImage") db, error := sql.Open("sqlite3", ws.RootDir+"/gypo.db") defer db.Close() if error != nil { html = []byte(error.Error()) } else { var path, filename string if strings.Index(r.URL.RawQuery, "&width=") == -1 || strings.Index(r.URL.RawQuery, "id=") == -1 { html = []byte("bad url") } else { fileId, error := strconv.Atoi(r.URL.RawQuery[strings.Index(r.URL.RawQuery, "id=")+3 : strings.Index(r.URL.RawQuery, "&width=")]) if error != nil { html = []byte(error.Error()) } else { error = db.QueryRow("SELECT path, filename number FROM files WHERE id = ?", fileId).Scan(&path, &filename) if error != nil { html = []byte(error.Error()) } else { pathfile := ws.RootDir + "/user-" + strconv.Itoa(userId) + path + filename image, error := magick.NewFromFile(pathfile) if error != nil { html = []byte(error.Error()) } else { defer image.Destroy() //if image wider than 50 % of screen; resize screenWidth, _ := strconv.Atoi(r.URL.RawQuery[strings.LastIndex(r.URL.RawQuery, "=")+1:]) var resizeFactor float32 resizeFactor = float32(screenWidth) * 50.0 / 100.0 if int(resizeFactor) < image.Width() { resizeFactor = resizeFactor / float32(image.Width()) error = image.Resize(strconv.Itoa(int(float32(image.Width())*resizeFactor)) + "x" + strconv.Itoa(int(float32(image.Height())*resizeFactor))) if error != nil { fmt.Println(error.Error()) } else { fmt.Println("image resized: " + filename) } fmt.Println("resizeFactor: ", resizeFactor) } if error != nil { html = []byte(error.Error()) } else { //reads image and writes it to buffer array html, error = image.ToBlob(filename[strings.LastIndex(filename, "."):]) if error != nil { html = []byte(error.Error()) fmt.Println(error.Error()) } else { //set headers according to file mimeStr := mime.TypeByExtension(filename[strings.LastIndex(filename, "."):]) fmt.Println("setting content-type: " + mimeStr) w.Header().Set("Content-Type", mimeStr) w.Header().Set("Content-Length", strconv.Itoa(len(html))) w.Header().Set("Content-Disposition", "inline; filename="+filename) fmt.Println("image sent, size: ", len(html), "\n") } } } } } } } } else { //unknown query html, error = ws.loadPage(r.URL.Path[1:]) if error != nil { html = []byte("could not find page") } } } } //writes output to client j, error := w.Write(html) if error != nil { fmt.Println(error.Error()) } else { fmt.Println("WebServer | bytes written: ", j) //writes amount written to client } }