Coder Social home page Coder Social logo

thezoraiz / ascii-image-converter Goto Github PK

View Code? Open in Web Editor NEW
1.9K 22.0 112.0 31.69 MB

A cross-platform command-line tool to convert images into ascii art and print them on the console. Now supports braille art!

License: Apache License 2.0

Go 100.00%
golang ascii-art ascii-image ascii command-line command-line-tool image-processing image-to-ascii converts-images linux

ascii-image-converter's Introduction

ascii-image-converter

release-version license language release-downloads ascii-image-converter-snap

ascii-image-converter is a command-line tool that converts images into ascii art and prints them out onto the console. Available on Windows, Linux and macOS.

Now supports braille art!

Input formats currently supported:

  • JPEG/JPG
  • PNG
  • BMP
  • WEBP
  • TIFF/TIF
  • GIF

Table of Contents

Installation

Debian or Ubuntu-based Distros

Execute the following commands in order:

echo 'deb [trusted=yes] https://apt.fury.io/ascii-image-converter/ /' | sudo tee /etc/apt/sources.list.d/ascii-image-converter.list
sudo apt update
sudo apt install -y ascii-image-converter

To remove the package source (which means you won't be getting any further updates), execute this command:

sudo rm -v /etc/apt/sources.list.d/ascii-image-converter.list

Homebrew

Installation with homebrew is available for both Linux and macOS.

brew install TheZoraiz/ascii-image-converter/ascii-image-converter

Link to homebrew repository


AUR

The AUR repo is maintained by magnus-tesshu

Standard way:

git clone https://aur.archlinux.org/ascii-image-converter-git.git
cd ascii-image-converter-git/
makepkg -si

AUR helper:

<aur-helper> -S ascii-image-converter-git

Scoop

The scoop manifest is maintained by brian6932

scoop install ascii-image-converter

Snap

Note: The snap will not have access to hidden files and files outside the $HOME directory. This includes write access for saving ascii art as well.

sudo snap install ascii-image-converter

Visit the app's snap store listing for instructions regarding enabling snapd on your distribution.

Get it from the Snap Store


Go

go install github.com/TheZoraiz/ascii-image-converter@latest

For physically installing the binaries, follow the steps with respect to your OS.

Linux

Download the archive for your distribution's architecture here, extract it, and open the extracted directory.

Now, open a terminal in the same directory and execute this command:

sudo cp ascii-image-converter /usr/local/bin/

Now you can use ascii-image-converter in the terminal. Execute ascii-image-converter -h for more details.

Windows

You will need to set an Environment Variable to the folder the ascii-image-converter.exe executable is placed in to be able to use it in the command prompt. Follow the instructions in case of confusion:

Download the archive for your Windows architecture here, extract it, and open the extracted folder. Now, copy the folder path from the top of the file explorer and follow these instructions:

  • In Search, search for and then select: Advanced System Settings
  • Click Environment Variables. In the section User Variables find the Path environment variable and select it. Click "Edit".
  • In the Edit Environment Variable window, click "New" and then paste the path of the folder that you copied initially.
  • Click "Ok" on all open windows.

Now, restart any open command prompt and execute ascii-image-converter -h for more details.


CLI Usage

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 multiple image paths and urls as well as a GIF.

ascii-image-converter [image paths/urls]

Example:

ascii-image-converter myImage.jpeg

Note: Piped binary input is also supported

cat myImage.png | ascii-image-converter -

Flags

--color OR -C

Note: Your terminal must support 24-bit or 8-bit colors for appropriate results. If 24-bit colors aren't supported, 8-bit color escape codes will be used

Display ascii art with the colors from original image.

ascii-image-converter [image paths/urls] -C
# Or
ascii-image-converter [image paths/urls] --color

--braille OR -b

Note: Braille pattern display heavily depends on which terminal or font you're using. In windows, try changing the font from command prompt properties if braille characters don't display

Use braille characters instead of ascii. For this flag, your terminal must support braille patters (UTF-8) properly. Otherwise, you may encounter problems with colored or even uncolored braille art.

ascii-image-converter [image paths/urls] -b
# Or
ascii-image-converter [image paths/urls] --braille

--threshold

Set threshold value to compare for braille art when converting each pixel into a dot. Value must be between 0 and 255.

Example:

ascii-image-converter [image paths/urls] -b --threshold 170

--dither

Apply dithering on image to make braille art more visible. Since braille dots can only be on or off, dithering images makes them more visible in braille art.

Example:

ascii-image-converter [image paths/urls] -b --dither

--color-bg

If any of the coloring flags is passed, this flag will transfer its color to each character's background. instead of foreground. However, this option isn't available for --save-img and --save-gif

ascii-image-converter [image paths/urls] -C --color-bg

--dimensions OR -d

Note: Don't immediately append another flag with -d

Set the width and height for ascii art in CHARACTER lengths.

ascii-image-converter [image paths/urls] -d <width>,<height>
# Or
ascii-image-converter [image paths/urls] --dimensions <width>,<height>

Example:

ascii-image-converter [image paths/urls] -d 60,30

--width OR -W

Note: Don't immediately append another flag with -W

Set width of ascii art. Height is calculated according to aspect ratio.

ascii-image-converter [image paths/urls] -W <width>
# Or
ascii-image-converter [image paths/urls] --width <width>

Example:

ascii-image-converter [image paths/urls] -W 60

--height OR -H

Note: Don't immediately append another flag with -H

Set height of ascii art. Width is calculated according to aspect ratio.

ascii-image-converter [image paths/urls] -H <height>
# Or
ascii-image-converter [image paths/urls] --height <height>

Example:

ascii-image-converter [image paths/urls] -H 60

--map OR -m

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.

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/urls] -m "<string-of-characters>"
# Or
ascii-image-converter [image paths/urls] --map "<string-of-characters>"

Following example contains 7 depths of lighting.

ascii-image-converter [image paths/urls] -m " .-=+#@"

--grayscale OR -g

Display ascii art in grayscale colors. This is the same as --color flag, except each character will be encoded with a grayscale RGB value.

ascii-image-converter [image paths/urls] -g
# Or
ascii-image-converter [image paths/urls] --grayscale

--negative OR -n

Display ascii art in negative colors. Works with both uncolored and colored text from --color flag.

ascii-image-converter [image paths/urls] -n
# Or
ascii-image-converter [image paths/urls] --negative

--complex OR -c

Print the image with a wider array of ascii characters for more detailed lighting density. Sometimes improves accuracy.

ascii-image-converter [image paths/urls] -c
# Or
ascii-image-converter [image paths/urls] --complex

--full OR -f

Print ascii art that fits the terminal width while maintaining aspect ratio.

ascii-image-converter [image paths/urls] -f
# Or
ascii-image-converter [image paths/urls] --full

--flipX OR -x

Flip the ascii art horizontally on the terminal.

ascii-image-converter [image paths/urls] --flipX
# Or
ascii-image-converter [image paths/urls] -x

--flipY OR -y

Flip the ascii art vertically on the terminal.

ascii-image-converter [image paths/urls] --flipY
# Or
ascii-image-converter [image paths/urls] -y

--save-img OR -s

Note: Don't immediately append another flag with -s

Saves the ascii as a PNG image with the name <image-name>-ascii-art.png in the directory path passed to the flag. Can work with both --color and --negative flag.

Example for current directory:

ascii-image-converter [image paths/urls] --save-img .
# Or
ascii-image-converter [image paths/urls] -s .

--save-txt

Similar to --save-img but it creates a TXT file with the name <image-name>-ascii-art.txt in the directory path passed to the flag. Only saves uncolored text.

Example for current directory:

ascii-image-converter [image paths/urls] --save-txt .

--save-gif

Note: This is an experimental feature and may not result in the finest quality GIFs, because all GIFs still aren't supported by ascii-image-converter.

Saves the passed GIF as an ascii art GIF with the name <image-name>-ascii-art.gif in the directory path passed to the flag.

--save-bg

Note: This flag will be ignored if --save-img or --save-gif flags are not set

This flag takes an RGBA value that sets the background color in saved png and gif files. The fourth value (alpha value) is the measure of background opacity ranging between 0 and 100.

ascii-image-converter [image paths/urls] -s . --save-bg 255,255,255,100 # For white background

--font

Note: This flag will be ignored if --save-img or --save-gif flags are not set

This flag takes path to a font .ttf file that will be used to set font in saved png or gif files.

ascii-image-converter [image paths/urls] -s . --font /path/to/font-file.ttf

--font-color

This flag takes an RGB value that sets the font color in saved png and gif files as well as displayed ascii art in terminal.

ascii-image-converter [image paths/urls] -s . --font-color 0,0,0 # For black font color

--only-save

Don't print ascii art on the terminal if some saving flag is passed.

ascii-image-converter [image paths/urls] -s . --only-save

--formats

Display supported input formats.

ascii-image-converter --formats

Library Usage

Note: The library may throw errors during Go tests due to some unresolved bugs with the consolesize-go package (Only during tests, not main program execution).

First, install the library with:

go get -u github.com/TheZoraiz/ascii-image-converter/aic_package

For an image:

package main

import (
	"fmt"

	"github.com/TheZoraiz/ascii-image-converter/aic_package"
)

func main() {
	// If file is in current directory. This can also be a URL to an image or gif.
	filePath := "myImage.jpeg"

	flags := aic_package.DefaultFlags()

	// This part is optional.
	// You can directly pass default flags variable to aic_package.Convert() if you wish.
	// There are more flags, but these are the ones shown for demonstration
	flags.Dimensions = []int{50, 25}
	flags.Colored = true
	flags.SaveTxtPath = "."
	flags.SaveImagePath = "."
	flags.CustomMap = " .-=+#@"
	flags.FontFilePath = "./RobotoMono-Regular.ttf" // If file is in current directory
	flags.SaveBackgroundColor = [4]int{50, 50, 50, 100}

	// Note: For environments where a terminal isn't available (such as web servers), you MUST
	// specify atleast one of flags.Width, flags.Height or flags.Dimensions

	// Conversion for an image
	asciiArt, err := aic_package.Convert(filePath, flags)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Printf("%v\n", asciiArt)
}

Note: GIF conversion is not advised as the function may run infinitely, depending on the GIF. More work needs to be done on this to make it more library-compatible.

For a GIF:

package main

import (
	"fmt"

	"github.com/TheZoraiz/ascii-image-converter/aic_package"
)

func main() {
	filePath = "myGif.gif"

	flags := aic_package.DefaultFlags()

	_, err := aic_package.Convert(filePath, flags)
	if err != nil {
		fmt.Println(err)
	}
}

Contributing

You can fork the project and implement any changes you want for a pull request. However, for major changes, please open an issue first to discuss what you would like to implement.

Packages Used

github.com/spf13/cobra

github.com/fogleman/gg

github.com/mitchellh/go-homedir

github.com/nathan-fiscaletti/consolesize-go

github.com/disintegration/imaging

github.com/gookit/color

github.com/makeworld-the-better-one/dither

License

Apache-2.0

ascii-image-converter's People

Contributors

atreyaved avatar brian6932 avatar jpagny avatar miniscruff avatar thezoraiz avatar xmarcos avatar zargham1214 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ascii-image-converter's Issues

panic: runtime error: index out of range [0] with length 0

Hi :)

Depending on which env i run it, it can result on:

$ ascii-image-converter ./my_image.png

panic: runtime error: index out of range [0] with length 0
goroutine 1 [running]:
github.com/TheZoraiz/ascii-image-converter/image_manipulation.ConvertToBrailleChars(0x0, 0x0, 0x0, 0x100, 0xff, 0xff, 0xff, 0x32, 0x0, 0x0, ...)
	/home/zozu/Stuff/Projects/ascii-image-converter/image_manipulation/ascii_conversions.go:180 +0xa6c
github.com/TheZoraiz/ascii-image-converter/aic_package.pathIsImage(0x7ffeae218883, 0xa, 0x0, 0x0, 0xc00000c300, 0x0, 0x0, 0x0, 0xc000010128, 0xc0000304f8, ...)
	/home/zozu/Stuff/Projects/ascii-image-converter/aic_package/convert_image.go:54 +0x2ee
github.com/TheZoraiz/ascii-image-converter/aic_package.Convert(0x7ffeae218883, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...)
	/home/zozu/Stuff/Projects/ascii-image-converter/aic_package/convert_root.go:157 +0x668
github.com/TheZoraiz/ascii-image-converter/cmd.glob..func1(0xd26560, 0xc0000a48c0, 0x1, 0x5)
	/home/zozu/Stuff/Projects/ascii-image-converter/cmd/root.go:97 +0x379
github.com/spf13/cobra.(*Command).execute(0xd26560, 0xc000020250, 0x5, 0x5, 0xd26560, 0xc000020250)
	/home/zozu/go/pkg/mod/github.com/spf13/[email protected]/command.go:856 +0x2c2
github.com/spf13/cobra.(*Command).ExecuteC(0xd26560, 0xc000000180, 0x200000003, 0xc000000180)
	/home/zozu/go/pkg/mod/github.com/spf13/[email protected]/command.go:960 +0x375
github.com/spf13/cobra.(*Command).Execute(...)
	/home/zozu/go/pkg/mod/github.com/spf13/[email protected]/command.go:897
github.com/TheZoraiz/ascii-image-converter/cmd.Execute()
	/home/zozu/Stuff/Projects/ascii-image-converter/cmd/root.go:118 +0x31
main.main()
	/home/zozu/Stuff/Projects/ascii-image-converter/main.go:22 +0x25

In this example, i launch it on a docker ubuntu 18 running inside a linux gitlab runner.
Any idea ?

Add ability to convert any io.Reader (or maybe any image.Image) to aic_package

Having aic_package.Convert handle opening local files or fetching remote files seems like it should be out of scope for a function that's just named Convert. Having it (or another function) handle a generic io.Reader or image.Image would be hugely useful. Right now it's not really possible to use aic_package to ascii-fy an embedded or generated image, for example.

more color format of output

I want to use ascii-image-converter to show image preview in ranger. But ranger does not support true color, so the preview in ranger looks wired.
I hope i can choose the output color format in commad line

Brew deprecated arguments

Gettings this error from brew:

Warning: Calling bottle :unneeded is deprecated! There is no replacement.
Please report this issue to the thezoraiz/ascii-image-converter tap (not Homebrew/brew or Homebrew/core):
  /opt/homebrew/Library/Taps/thezoraiz/homebrew-ascii-image-converter/ascii-image-converter.rb:10

Wired color

When using the command "-C", image coloring looks wired.
Screen Shot 2021-09-10 at 8 14 53 AM

Unable to only save with color using go library

I am using the go library where a terminal isn't available. It works fine without color, but is throwing error when I set color flag to true

Error:

your terminal supports neither 24-bit nor 8-bit colors. Other coloring options aren't available

Code:

width, err := strconv.Atoi(os.Getenv("WIDTH"))
if err != nil {
  panic(err)
}
color := os.Getenv("COLOR")
if len(color) == 0 {
   color = "false" 
}
color_bool, err := strconv.ParseBool(os.Getenv("COLOR"))
if err != nil {
  panic(err)
}
fmt.Println("filename: " + file)
flags := aic_package.DefaultFlags()
flags.SaveImagePath = "."
flags.Colored = color_bool
flags.OnlySave = true
flags.Dimensions = []int{width * 2, width}
fmt.Println("the flags are "+ strconv.FormatBool(flags.OnlySave))
asciiArt, err := aic_package.Convert(file, flags)
if err != nil {
  fmt.Println(err)
}
if (len(asciiArt)>0){
  fmt.Printf("the converted file is %v\n", asciiArt)
}

How can I save a colored ASCII file?

Wrong -C output

When I use the "-C" to display the output, the result is wired. The image saved using "--save-img" seems to be fine.

the output displayed in the terminal.
image

the saved result
leo-ascii-art

Clear ansi-colored output

  1. When characters in the row have the same color, will be better print escape code only once: \e[38;5;20mw\e[38;5;20mm -> \e[38;5;20mwm
  2. Use only space as invisible character, when background and text have same color: \e[38;5;0m<char> -> \e[38;5;0m

Also, will be cool mixing --color and --color-bg. Maybe, in form --color=(fg|bg|both)

Phone portrait mode photos are rotated by 90°

When converting images shot on a smartphone in portrait mode, the output is rotated anti-clockwise by 90°. This might have to do with the image metadata not being read properly, or at least not the part that tells that the image is rotated 90°.

This is the exact same issue as Talinx/jp2a#13

Docker image

Hi,

ascii-image-converter just created the perfect startup banner for our spring boot application. Thanks a bunch!

As already noted, packaging is not trivial. A docker image for ascii-image-converter would make usage easier without the need for any local installation.

I am attaching a Dockerfile that created a well usable image for me.
Dockerfile.ascii-image-converter.txt

(Usage: place in a working directory, such as an empty dir or the local git repo, execute docker build -t ascii-image-converter -f Dockerfile.ascii-image-converter.txt .. Usage of resulting image: docker run --rm -it ascii-image-converter <url>, or docker run -v $(pwd):/data --rm -it ascii-image-converter /data/<localfile>).

Would you be interested in providing an "official" image on docker hub?

If you prefer the file as a pull request, just give me a note.

Feature Request: bin piping support

It would be useful to be able quickly convert an image from stdin, like this:

curl -sSL https:/foo.bar/baz.qux | ascii-image-converter

or

curl -sSL https:/foo.bar/baz.qux | ascii-image-converter -

and can allow some more mixups like:

curl -sSL https:/foo.bar/baz.qux | magick convert - png:- | ascii-image-converter

or

curl -sSL https:/foo.bar/baz.qux | magick convert - png:- | ascii-image-converter -

I personally prefer doing it by default, but either one is fine by me 🤷

No option to save with color?

I'm confused why the only two options are to save as an image (with color, but unable to be displayed in the terminal), or as uncolored text. Why is this not supported? I just want a file which includes the text and the escape sequences.

changes to go.mod enables "default" installation

I read your reddit post and tried to install your tool using the "default" go way of doing this:

go get -u go get -u github.com/TheZoraiz/ascii-image-converter
go install github.com/TheZoraiz/ascii-image-converter@latest

This would esentially work if the first line of your go.mod file was like this:

module github.com/TheZoraiz/ascii-image-converter

Best regards

Save output to ansi text file

Is there a way to save the output as an ansi text file? If I try to redirect output, it barfs during terminal size detection. If I also specify the output size with -d, it complains the terminal is too small.

Update: I was able to capture the output using script but it would certainly be nice to have a proper save-as-ansi option.

macOS version

👋 , first of all, thanks for this tool, it's awesome :)

I was wondering why you don't include a macOS version.

I was able to build ascii-image-converter locally (on Big Sur) without problems and since you are using goreleaser, it shouldn't take more than including darwin in the target goos.

So, if there is no particular reason against it, i'd love to have a release for mac. I have little experience with go, but I'm happy to send an initial PR to get this going. Let me know!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.