diff --git a/src/internal/web/download.go b/src/internal/web/download.go index ce84275..6002d3f 100644 --- a/src/internal/web/download.go +++ b/src/internal/web/download.go @@ -1,19 +1,33 @@ package web import ( + "image" + "image/jpeg" "io" "net/http" "os" + "path" + + "github.com/nfnt/resize" ) // Download used for downloading file var Download = func(srcURL, dest string) error { + if err := createDirectory(dest); err != nil { + return err + } + resp, err := http.Get(srcURL) if err != nil { return err } defer resp.Body.Close() + img, err := resizeImage(resp.Body) + if err != nil { + return err + } + // Create the file file, err := os.Create(dest) if err != nil { @@ -21,10 +35,19 @@ var Download = func(srcURL, dest string) error { } defer file.Close() - // Write from the net to the file - _, err = io.Copy(file, resp.Body) - if err != nil { - return err - } - return nil + return jpeg.Encode(file, img, nil) +} + +// createDirectory creates the destination directory +func createDirectory(dest string) error { + return os.MkdirAll(path.Dir(dest), os.ModePerm) +} + +func resizeImage(img io.Reader) (image.Image, error) { + image, _, err := image.Decode(img) + if err != nil { + return nil, err + } + + return resize.Resize(300, 0, image, resize.Lanczos3), nil }