Added url support and improved error handling

This commit is contained in:
Zoraiz 2021-05-29 01:32:51 +05:00
parent dfb81e08d2
commit 01401cfd37
8 changed files with 160 additions and 116 deletions

View File

@ -38,7 +38,9 @@ archives:
arm64: 64bit_arm64 arm64: 64bit_arm64
checksum: checksum:
name_template: 'checksums.txt' name_template: 'sha256_checksums.txt'
algorithm: sha256
snapshot: snapshot:
name_template: "{{ .Version }}-next" name_template: "{{ .Version }}-next"
changelog: changelog:

View File

@ -83,10 +83,10 @@ Now, restart any open command prompt and execute "ascii-image-converter -h" for
Note: Decrease font size or increase terminal width (like zooming out) for maximum quality ascii art Note: Decrease font size or increase terminal width (like zooming out) for maximum quality ascii art
The basic usage for converting an image into ascii art is as follows. You can also supply paths to multiple images. The basic usage for converting an image into ascii art is as follows. You can also supply multiple image paths and urls.
``` ```
ascii-image-converter [image-paths] ascii-image-converter [image paths/urls]
``` ```
Example: Example:
``` ```
@ -100,18 +100,18 @@ ascii-image-converter myImage.jpeg
Display ascii art with the colors from original image. Works with the --negative flag as well. Display ascii art with the colors from original image. Works with the --negative flag as well.
``` ```
ascii-image-converter [image-paths] -C ascii-image-converter [image paths/urls] -C
# Or # Or
ascii-image-converter [image-paths] --color ascii-image-converter [image paths/urls] --color
``` ```
#### --complex OR -c #### --complex OR -c
Print the image with a wider array of ascii characters for more detailed lighting density. Sometimes improves accuracy. Print the image with a wider array of ascii characters for more detailed lighting density. Sometimes improves accuracy.
``` ```
ascii-image-converter [image-paths] -c ascii-image-converter [image paths/urls] -c
# Or # Or
ascii-image-converter [image-paths] --complex ascii-image-converter [image paths/urls] --complex
``` ```
#### --dimensions OR -d #### --dimensions OR -d
@ -120,13 +120,13 @@ Note: Don't immediately append another flag with -d
Set the width and height for ascii art in CHARACTER lengths. Set the width and height for ascii art in CHARACTER lengths.
``` ```
ascii-image-converter [image-paths] -d <width>,<height> ascii-image-converter [image paths/urls] -d <width>,<height>
# Or # Or
ascii-image-converter [image-paths] --dimensions <width>,<height> ascii-image-converter [image paths/urls] --dimensions <width>,<height>
``` ```
Example: Example:
``` ```
ascii-image-converter [image-paths] -d 100,30 ascii-image-converter [image paths/urls] -d 100,30
``` ```
#### --map OR -m #### --map OR -m
@ -135,16 +135,16 @@ Note: Don't immediately append another flag with -m
Pass a string of your own ascii characters to map against. Passed characters must start from darkest character and end with lightest. There is no limit to number of characters. Pass a string of your own ascii characters to map against. Passed characters must start from darkest character and end with lightest. There is no limit to number of characters.
Notes: Empty spaces can be passed if string is passed inside quotation marks. You can use both single or double quote for quotation marks. For repeating quotation mark inside string, append it with \ (such as \\"). Empty spaces can be passed if string is passed inside quotation marks. You can use both single or double quote for quotation marks. For repeating quotation mark inside string, append it with \ (such as \\").
``` ```
ascii-image-converter [image-paths] -m "<string-of-characters>" ascii-image-converter [image paths/urls] -m "<string-of-characters>"
# Or # Or
ascii-image-converter [image-paths] --map "<string-of-characters>" ascii-image-converter [image paths/urls] --map "<string-of-characters>"
``` ```
Following example contains 7 depths of lighting. Following example contains 7 depths of lighting.
``` ```
ascii-image-converter [image-paths] -m " .-=+#@" ascii-image-converter [image paths/urls] -m " .-=+#@"
``` ```
#### --negative OR -n #### --negative OR -n
@ -152,23 +152,23 @@ ascii-image-converter [image-paths] -m " .-=+#@"
Display ascii art in negative colors. Works with both uncolored and colored text from --color flag. Display ascii art in negative colors. Works with both uncolored and colored text from --color flag.
``` ```
ascii-image-converter [image-paths] -n ascii-image-converter [image paths/urls] -n
# Or # Or
ascii-image-converter [image-paths] --negative ascii-image-converter [image paths/urls] --negative
``` ```
#### --save OR -s #### --save OR -s
Note: Don't immediately append another flag with -s Note: Don't immediately append another flag with -s
Save ascii art in the format `<image-name>-<image-extension>-ascii-art.txt` in the directory path passed to the flag. Save ascii art in the format `<image-name>.<image-extension>-ascii-art.txt` in the directory path passed to the flag.
Example for current directory: Example for current directory:
``` ```
ascii-image-converter [image-paths] --save . ascii-image-converter [image paths/urls] --save .
# Or # Or
ascii-image-converter [image-paths] -s . ascii-image-converter [image paths/urls] -s .
``` ```
#### --formats OR -f #### --formats OR -f
@ -176,16 +176,16 @@ ascii-image-converter [image-paths] -s .
Display supported image formats. Display supported image formats.
``` ```
ascii-image-converter [image-paths] --formats ascii-image-converter [image paths/urls] --formats
# Or # Or
ascii-image-converter [image-paths] -f ascii-image-converter [image paths/urls] -f
``` ```
<br> <br>
You can combine flags as well. Following command outputs colored and negative ascii art, with fixed 100 by 30 character dimensions, custom defined ascii characters " .-=+#@" and saves the output in current directory as well. You can combine flags as well. Following command outputs colored and negative ascii art, with fixed 100 by 30 character dimensions, custom defined ascii characters " .-=+#@" and saves the output in current directory as well.
``` ```
ascii-image-converter [image-paths] -Cnd 100,30 -m " .-=+#@" -s ./ ascii-image-converter [image paths/urls] -Cnd 100,30 -m " .-=+#@" -s ./
``` ```
<br> <br>
@ -196,8 +196,6 @@ You can fork the project and implement any changes you want for a pull request.
## Packages used ## Packages used
[github.com/spf13/viper](https://github.com/spf13/viper)
[github.com/spf13/cobra](https://github.com/spf13/cobra) [github.com/spf13/cobra](https://github.com/spf13/cobra)
[github.com/mitchellh/go-homedir](https://github.com/mitchellh/go-homedir) [github.com/mitchellh/go-homedir](https://github.com/mitchellh/go-homedir)
@ -208,6 +206,8 @@ You can fork the project and implement any changes you want for a pull request.
[github.com/gookit/color](https://github.com/gookit/color) [github.com/gookit/color](https://github.com/gookit/color)
[github.com/asaskevich/govalidator](https://github.com/asaskevich/govalidator)
## License ## License
[Apache-2.0](https://github.com/TheZoraiz/ascii-image-converter/blob/master/LICENSE.txt) [Apache-2.0](https://github.com/TheZoraiz/ascii-image-converter/blob/master/LICENSE.txt)

View File

@ -16,11 +16,13 @@ limitations under the License.
package cmd package cmd
import ( import (
"bytes"
"fmt" "fmt"
"image" "image"
"io/ioutil" "io/ioutil"
"net/http"
"os" "os"
"path/filepath" "path"
"strings" "strings"
// Image format initialization // Image format initialization
@ -33,10 +35,9 @@ import (
_ "golang.org/x/image/webp" _ "golang.org/x/image/webp"
imgMani "github.com/TheZoraiz/ascii-image-converter/image_manipulation" imgMani "github.com/TheZoraiz/ascii-image-converter/image_manipulation"
"github.com/asaskevich/govalidator"
"github.com/spf13/cobra"
homedir "github.com/mitchellh/go-homedir" homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -53,37 +54,39 @@ var (
// Root commands // Root commands
rootCmd = &cobra.Command{ rootCmd = &cobra.Command{
Use: "ascii-image-converter [image-paths]", Use: "ascii-image-converter [image paths/urls]",
Short: "Converts images into ascii format", Short: "Converts images into ascii art",
Version: "1.2.4", Version: "1.2.5",
Long: "This tool converts images into ascii art and prints them on the terminal.\nFurther configuration can be managed with flags.", Long: "This tool converts images into ascii art and prints them on the terminal.\nFurther configuration can be managed with flags.",
RunE: func(cmd *cobra.Command, args []string) error {
// Not RunE since help text is getting larger and seeing it for every error impacts user experience
Run: func(cmd *cobra.Command, args []string) {
if formatsTrue { if formatsTrue {
fmt.Println("Supported image formats: JPEG/JPG, PNG, WEBP, BMP, TIFF/TIF") fmt.Printf("Supported image formats: JPEG/JPG, PNG, WEBP, BMP, TIFF/TIF\n\n")
return nil return
} }
numberOfDimensions := len(dimensions) numberOfDimensions := len(dimensions)
if dimensions != nil && numberOfDimensions != 2 { if dimensions != nil && numberOfDimensions != 2 {
return fmt.Errorf("-d requires 2 dimensions, got %v", numberOfDimensions) fmt.Printf("-d requires 2 dimensions, got %v\n\n", numberOfDimensions)
return
} }
if len(args) < 1 { if len(args) < 1 {
return fmt.Errorf("Need at least 1 image path") fmt.Printf("Error: Need at least 1 image path/url\n\n")
cmd.Help()
return
} }
if len(customMap) < 2 && customMap != "" { if customMap != "" && len(customMap) < 2 {
fmt.Println("Need at least 2 characters") fmt.Printf("Need at least 2 characters for --map flag\n\n")
os.Exit(0) return
} }
for _, imagePath := range args { for _, imagePath := range args {
if err := convertImage(imagePath); err != nil { convertImage(imagePath)
return err
}
} }
return nil
}, },
} }
) )
@ -96,97 +99,87 @@ func checkOS() string {
} }
} }
func convertImage(imagePath string) error { func convertImage(imagePath string) {
pic, err := os.Open(imagePath) // Declared at the start since some variables are initially used in conditional blocks
if err != nil { var pic *os.File
fmt.Printf("Unable to open file: %v\n", err) var urlImgBytes []byte
os.Exit(0) var urlImgName string = ""
var err error
pathIsURl := govalidator.IsRequestURL(imagePath)
// Different modes of reading data depending upon whether or not imagePath is a url
if pathIsURl {
fmt.Printf("Fetching image from url...\r")
retrievedImage, err := http.Get(imagePath)
if err != nil {
fmt.Printf("Error fetching image: %v\n\n", err)
return
}
urlImgBytes, err = ioutil.ReadAll(retrievedImage.Body)
if err != nil {
fmt.Printf("Failed to read fetched content: %v\n\n", err)
return
}
defer retrievedImage.Body.Close()
urlImgName = path.Base(imagePath)
fmt.Printf(" \r") // To erase "Fetching image from url..." text from console
} else {
pic, err = os.Open(imagePath)
if err != nil {
fmt.Printf("Unable to open file: %v\n\n", err)
return
}
defer pic.Close()
} }
defer pic.Close()
imData, _, err := image.Decode(pic) var imData image.Image
if pathIsURl {
imData, _, err = image.Decode(bytes.NewReader(urlImgBytes))
} else {
imData, _, err = image.Decode(pic)
}
if err != nil { if err != nil {
fmt.Printf("Error decoding file: %v\n", err) fmt.Printf("Error decoding %v. %v\n\n", imagePath, err)
os.Exit(0) return
} }
imgSet, err := imgMani.ConvertToAsciiPixels(imData, dimensions) imgSet, err := imgMani.ConvertToAsciiPixels(imData, dimensions)
if err != nil { if err != nil {
fmt.Printf("Error: %v\n", err) fmt.Printf("Error: %v\n\n", err)
os.Exit(0) return
} }
var asciiSet [][]imgMani.AsciiChar asciiSet := imgMani.ConvertToAscii(imgSet, negative, colored, compl, customMap)
asciiSet = imgMani.ConvertToAscii(imgSet, negative, colored, compl, customMap)
var ascii []string ascii := flattenAscii(asciiSet, colored)
ascii = flattenAscii(asciiSet, colored)
// Save art before printing it, if flag is passed // Save ascii art before printing it, if --save flag is passed
if savePath != "" { if savePath != "" {
if err := saveAsciiArt(asciiSet, imagePath); err != nil { if err := saveAsciiArt(asciiSet, imagePath, urlImgName); err != nil {
fmt.Printf("Error: %v\n", err) fmt.Printf("Error: %v\n\n", err)
os.Exit(0) os.Exit(0) // Because this error will be thrown for every image passed to this function if we use "return"
} }
} }
for _, line := range ascii { for _, line := range ascii {
fmt.Println(line) fmt.Println(line)
} }
return nil
}
func saveAsciiArt(asciiSet [][]imgMani.AsciiChar, imagePath string) error {
// To make sure uncolored ascii art is the one saved
saveAscii := flattenAscii(asciiSet, false)
saveFileName, err := createSaveFileName(imagePath)
if err != nil {
return err
}
savePathLastChar := string(savePath[len(savePath)-1])
// Check if path is closed with appropriate path separator
if savePathLastChar != string(os.PathSeparator) {
if checkOS() == "linux" {
savePath += "/"
} else if checkOS() == "windows" {
savePath += "\\"
} else {
return fmt.Errorf("Path not identified. OS isn't supported")
}
}
// If path exists
if _, err := os.Stat(savePath); !os.IsNotExist(err) {
return ioutil.WriteFile(savePath+saveFileName, []byte(strings.Join(saveAscii, "\n")), 0777)
} else {
return fmt.Errorf("Save path does not exist.")
}
}
func createSaveFileName(imagePath string) (string, error) {
fileInfo, err := os.Stat(imagePath)
if err != nil {
return "", fmt.Errorf("Can't read file info for saving ascii art.")
}
currName := fileInfo.Name()
extension := filepath.Ext(imagePath)
newName := currName[:len(currName)-len(extension)]
// Something like myImage-jpeg-ascii-art.txt
return newName + "-" + extension[1:] + "-ascii-art.txt", nil
} }
// flattenAscii flattens a two-dimensional grid of ascii characters into a one dimension // flattenAscii flattens a two-dimensional grid of ascii characters into a one dimension
// of lines of ascii // of lines of ascii
func flattenAscii(asciiSet [][]imgMani.AsciiChar, color bool) []string { func flattenAscii(asciiSet [][]imgMani.AsciiChar, color bool) []string {
var ascii []string var ascii []string
for _, line := range asciiSet { for _, line := range asciiSet {
var tempAscii []string var tempAscii []string
for i := 0; i < len(line); i++ { for i := 0; i < len(line); i++ {
if color { if color {
tempAscii = append(tempAscii, line[i].Colored) tempAscii = append(tempAscii, line[i].Colored)
@ -194,11 +187,59 @@ func flattenAscii(asciiSet [][]imgMani.AsciiChar, color bool) []string {
tempAscii = append(tempAscii, line[i].Simple) tempAscii = append(tempAscii, line[i].Simple)
} }
} }
ascii = append(ascii, strings.Join(tempAscii, "")) ascii = append(ascii, strings.Join(tempAscii, ""))
} }
return ascii return ascii
} }
func saveAsciiArt(asciiSet [][]imgMani.AsciiChar, imagePath string, urlImgName string) error {
// To make sure uncolored ascii art is the one saved
saveAscii := flattenAscii(asciiSet, false)
saveFileName, err := createSaveFileName(imagePath, urlImgName)
if err != nil {
return err
}
savePathLastChar := string(savePath[len(savePath)-1])
// Check if path is closed with appropriate path separator (depending on OS)
if savePathLastChar != string(os.PathSeparator) {
if checkOS() == "linux" {
savePath += "/"
} else {
savePath += "\\"
}
}
// If path exists
if _, err := os.Stat(savePath); !os.IsNotExist(err) {
return ioutil.WriteFile(savePath+saveFileName, []byte(strings.Join(saveAscii, "\n")), 0666)
} else {
return fmt.Errorf("Save path does not exist.")
}
}
func createSaveFileName(imagePath string, urlImgName string) (string, error) {
if urlImgName != "" {
return urlImgName + "-ascii-art.txt", nil
}
fileInfo, err := os.Stat(imagePath)
if err != nil {
return "", err
}
currName := fileInfo.Name()
currExt := path.Ext(currName)
newName := currName[:len(currName)-len(currExt)] // e.g. Grabs myImage from myImage.jpeg
// Something like myImage.jpeg-ascii-art.txt
return newName + "." + currExt[1:] + "-ascii-art.txt", nil
}
// Cobra configuration from here on // Cobra configuration from here on
func Execute() { func Execute() {
@ -218,7 +259,7 @@ func init() {
rootCmd.PersistentFlags().BoolVarP(&formatsTrue, "formats", "f", false, "Display supported image formats\n") rootCmd.PersistentFlags().BoolVarP(&formatsTrue, "formats", "f", false, "Display supported image formats\n")
rootCmd.PersistentFlags().StringVarP(&customMap, "map", "m", "", "Give custom ascii characters to map against\nOrdered from darkest to lightest\ne.g. -m \" .-+#@\" (Quotation marks excluded from map)\n(Cancels --complex flag)\n") rootCmd.PersistentFlags().StringVarP(&customMap, "map", "m", "", "Give custom ascii characters to map against\nOrdered from darkest to lightest\ne.g. -m \" .-+#@\" (Quotation marks excluded from map)\n(Cancels --complex flag)\n")
rootCmd.PersistentFlags().BoolVarP(&negative, "negative", "n", false, "Display ascii art in negative colors\n(Can work with the --color flag)\n") rootCmd.PersistentFlags().BoolVarP(&negative, "negative", "n", false, "Display ascii art in negative colors\n(Can work with the --color flag)\n")
rootCmd.PersistentFlags().StringVarP(&savePath, "save", "s", "", "Save ascii art in the format:\n<image-name>-<image-extension>-ascii-art.txt\nFile will be saved in passed path\n(pass . for current directory)\n") rootCmd.PersistentFlags().StringVarP(&savePath, "save", "s", "", "Save ascii art in the format:\n<image-name>.<image-extension>-ascii-art.txt\nFile will be saved in passed path\n(pass . for current directory)\n")
defaultUsageTemplate := rootCmd.UsageTemplate() defaultUsageTemplate := rootCmd.UsageTemplate()
rootCmd.SetUsageTemplate("\nCopyright © 2021 Zoraiz Hassan <hzoraiz8@gmail.com>\n" + rootCmd.SetUsageTemplate("\nCopyright © 2021 Zoraiz Hassan <hzoraiz8@gmail.com>\n" +

1
go.mod
View File

@ -3,6 +3,7 @@ module github.com/TheZoraiz/ascii-image-converter
go 1.16 go 1.16
require ( require (
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
github.com/fsnotify/fsnotify v1.4.9 // indirect github.com/fsnotify/fsnotify v1.4.9 // indirect
github.com/gookit/color v1.4.2 github.com/gookit/color v1.4.2
github.com/magiconair/properties v1.8.5 // indirect github.com/magiconair/properties v1.8.5 // indirect

2
go.sum
View File

@ -19,6 +19,8 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d h1:Byv0BzEl3/e6D5CLfI0j/7hiIEtvGVFPCZ7Ei2oq8iQ=
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=

View File

@ -39,7 +39,6 @@ type AsciiPixel struct {
func ConvertToAsciiPixels(img image.Image, dimensions []int) ([][]AsciiPixel, error) { func ConvertToAsciiPixels(img image.Image, dimensions []int) ([][]AsciiPixel, error) {
var asciiWidth, asciiHeight int var asciiWidth, asciiHeight int
var smallImg image.Image var smallImg image.Image
if len(dimensions) == 0 { if len(dimensions) == 0 {
@ -59,7 +58,8 @@ func ConvertToAsciiPixels(img image.Image, dimensions []int) ([][]AsciiPixel, er
// If ascii width exceeds terminal width, change ratio with respect to terminal width // If ascii width exceeds terminal width, change ratio with respect to terminal width
if asciiWidth > terminalWidth { if asciiWidth > terminalWidth {
smallImg = resize.Resize(uint(terminalWidth), 0, img, resize.Lanczos3) smallImg = resize.Resize(uint(terminalWidth), 0, img, resize.Lanczos3)
asciiWidth = terminalWidth
asciiWidth = terminalWidth - 1
asciiHeight = smallImg.Bounds().Max.Y - smallImg.Bounds().Min.Y asciiHeight = smallImg.Bounds().Max.Y - smallImg.Bounds().Min.Y
// To fix aspect ratio in eventual ascii art // To fix aspect ratio in eventual ascii art

View File

@ -16,9 +16,7 @@ limitations under the License.
package main package main
import ( import "github.com/TheZoraiz/ascii-image-converter/cmd"
"github.com/TheZoraiz/ascii-image-converter/cmd"
)
func main() { func main() {
cmd.Execute() cmd.Execute()

View File

@ -1,7 +1,7 @@
name: ascii-image-converter name: ascii-image-converter
base: core18 base: core18
version: "1.2.4" version: "1.2.5"
summary: Converts images into ascii format summary: Converts images into ascii art
description: | description: |
This tool converts images into ascii format and prints them onto the terminal window. This tool converts images into ascii format and prints them onto the terminal window.
Supported image formats are JPEG/JPG, PNG, WEBP, BMP and TIFF/TIF. Further configuration can be managed by flags. Supported image formats are JPEG/JPG, PNG, WEBP, BMP and TIFF/TIF. Further configuration can be managed by flags.
@ -27,4 +27,4 @@ apps:
architectures: architectures:
- build-on: amd64 - build-on: amd64
run-on: [arm64, armhf, amd64, i386] run-on: [amd64, i386, arm64, armhf, s390x, ppc64el]