Skip to content

Commit

Permalink
feat: add support for urls
Browse files Browse the repository at this point in the history
  • Loading branch information
scottmckendry committed May 30, 2024
1 parent e009232 commit 67d183e
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
17 changes: 14 additions & 3 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
"fmt"
"image"
"os"

"github.com/spf13/cobra"
Expand All @@ -22,12 +23,22 @@ var cmd = &cobra.Command{

Run: func(cmd *cobra.Command, args []string) {
path := args[0]
if !PathExists(path) {
url := img.IsUrl(path)

if !url && !PathExists(path) {
cobra.CheckErr(fmt.Errorf("could not find file: %s", path))
}

image, err := img.Decode(path)
cobra.CheckErr(err)
image := image.Image(nil)
err := error(nil)
if !url {
image, err = img.Decode(path)
} else {
image, err = img.DecodeFromUrl(path)
}
if err != nil {
cobra.CheckErr(err)
}

columns, _ := cmd.Flags().GetInt("columns")
rows, _ := cmd.Flags().GetInt("rows")
Expand Down
20 changes: 20 additions & 0 deletions img/img.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"net/http"
"os"

"github.com/nfnt/resize"
Expand Down Expand Up @@ -49,3 +50,22 @@ func Resize(image image.Image, width, height int) image.Image {

return image
}

func DecodeFromUrl(url string) (image.Image, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()

img, _, err := image.Decode(resp.Body)
if err != nil {
return nil, err
}

return img, nil
}

func IsUrl(path string) bool {
return path[:4] == "http"
}

0 comments on commit 67d183e

Please sign in to comment.