Compare commits

...

79 commits

Author SHA1 Message Date
GitHub Actions
4d21a05d80 Update CImg to v.3.3.6 2024-06-03 00:28:47 +00:00
GitHub Actions
a5b9c64c7a Update CImg to v.3.3.5 2024-04-17 20:26:24 +00:00
Aaron Liu
56bac07109
try checkoutv2 per https://github.com/actions/checkout/issues/664 2024-04-02 22:22:36 -04:00
Quentin Santos
92cf12d2ec Fix some minor typos 2024-03-23 10:36:25 +01:00
Aaron Liu
84a3616796
fix entry point display and remove spurious newlines 2024-03-20 16:29:33 -04:00
Stefan Haustein
38ec4249b8 small fixes 2024-03-20 20:59:16 +01:00
Stefan Haustein
df32d7e1c1 Updated README, pointing at the API. 2024-03-20 20:14:42 +01:00
Stefan Haustein
8aca9afaf7 cleanup / formatting 2024-03-06 18:51:31 +01:00
Stefan Haustein
917b381bc3 preparation for more character groups 2024-03-06 18:37:16 +01:00
GitHub Actions
a18c4e62c6 Update CImg to v.3.3.4 2024-03-03 00:27:09 +00:00
Stefan Haustein
e5787c0288 Slight reformatting 2024-02-21 20:41:27 +01:00
Stefan Haustein
2fa6ece556 Change getPixel to actually transfer a full pixel with all channels 2024-02-21 20:34:50 +01:00
Aaron Liu
4cb242b7f5
re-add error message formatting from 7b5d790 2024-02-17 14:14:32 -05:00
Stefan Haustein
b783c67f66 split tiv_lib.h/.cpp out of tiv.cpp, adressing issue #52 2024-02-14 20:36:34 +01:00
Stefan Haustein
8c9ca72902 slightly re-word the license. 2024-02-14 19:55:08 +01:00
Stefan Haustein
a901624905 Replace constants copied from sysexits.h with our own definitions 2024-02-14 19:51:05 +01:00
Stefan Haustein
1c2c1c27e8 Always define the exit codes locally -- even on posix. 2024-02-14 19:23:02 +01:00
Alessandro de Oliveira Faria (A.K.A.CABELO)
190689961e
Fix @cabelo's name (#139)
Sorry!
2024-02-11 21:29:12 -05:00
Aaron Liu
a216fc64eb
Workflow for updating CImg (#137)
Also updates CImg to 3.3.3... huh, coincidence? <!-- I think not -->
2024-02-02 16:28:03 -05:00
Aaron Liu
ca97659f83
redo 9969dd1 2024-02-01 18:30:28 -05:00
Aaron Liu
dedaa1b7c2
redo 7b5d790 and f51dc08 2024-02-01 18:27:29 -05:00
Aaron Liu
3373e02e4c
CI: say chosen image name and only trigger if src files are modified or we want it to 2024-02-01 18:21:13 -05:00
Aaron Liu
4e1709a7c5
downgrade needed c++ to 17 2024-02-01 18:20:56 -05:00
Stefan Haustein
cc4b4b30bd
Update README.md
Clean up the installation options
2024-02-01 18:20:55 -05:00
Stefan Haustein
516107ca4f
Update README.md
Add another hint to install ImageMagic to the common problems / troubleshooting section.
2024-02-01 18:20:55 -05:00
Aaron Liu
8d785902e6
merge 2024-02-01 18:20:49 -05:00
Stefan Haustein
bc2d21db09
change format to string streams, as format is only available in 0x20, which complicates compiling on a mac 2024-02-01 18:18:59 -05:00
Aaron Liu
a64e5527a9
Add news and license note 2024-02-01 18:18:58 -05:00
Aaron Liu
e70f05fdf6
test dir mode and add more images that could be tested 2024-02-01 18:18:58 -05:00
Aaron Liu
7b5d7907d1
fix spurious size detect error and format error messages from system
TODO: fix unexpanded tilde on Windows
2024-02-01 18:18:50 -05:00
Aaron Liu
497b533010
hopefully this fixes gcc 2024-02-01 18:16:53 -05:00
Aaron Liu
c6b8855930
fix CI to force gcc 13 2024-02-01 18:14:28 -05:00
Aaron Liu
ac334fdfaa
lots of changes after a lot of time
rewrote some functions to use an accompanying function that returns a string; this prepares for splitting us into a library
fixed weird bug caused by CImg update
some endls have been replaced with \n
slightly more consistent function naming
more comments

1.3 part 1 out of ?
2024-02-01 18:14:27 -05:00
Aaron Liu
d9c1b47816
fix last commit 2024-02-01 18:14:23 -05:00
Aaron Liu
7b3c8286fe
make positioning of flags in emitTermColor consistent with other funcs 2024-02-01 18:13:31 -05:00
Aaron Liu
f51dc08b0a
correct image size in warning
it's 20x6, not 80x24
2024-02-01 18:07:20 -05:00
Aaron Liu
e636a03c13
separate print and string generation functions
string generation during image processing now have their own functions
2024-02-01 18:05:50 -05:00
Aaron Liu
9969dd1cff
rename some functions
change emit to print; emit will be used for things that generate strings/streams
use camelCase, closer to google style
specify that color is terminal color
2024-02-01 18:04:23 -05:00
Aaron Liu
c001eca18d
minor optimizations & bump version
make flags an int8_t
replace excessive instances of endl with \n
make a boolean const with better assignment
2024-02-01 18:01:06 -05:00
Aaron Liu
e72b11d359
more comments 2024-02-01 17:52:19 -05:00
Aaron Liu
e358e372ec
fix weird CImg bug 2024-02-01 17:49:14 -05:00
Stefan Haustein
0bfc892f4f Use a function reference instead of a cimg object for the inner conversion methods. Preparation for factoring them out to a separate file (tiv_lib.h / .cpp) 2024-02-01 21:22:39 +01:00
Stefan Haustein
bba4a692db clarify comments some more 2024-01-24 20:13:28 +01:00
Stefan Haustein
512b3dd91c Align license header with README.md 2024-01-24 19:55:40 +01:00
Stefan Haustein
1154264c54 Clarify / clean up some comments 2024-01-24 19:49:07 +01:00
Aaron Liu
71d1a80d14
PR #136 from penguin359/penguin359-ci: Basic testing CI 2024-01-19 14:18:41 -05:00
Loren M. Lang
ba7bafe092
Dropped install and don't restrict color palette during test 2024-01-19 11:15:19 -08:00
Loren M. Lang
2b46a7a227 Specifiy specific size and colors 2024-01-16 21:41:27 -08:00
Loren M. Lang
8f91b297f1 Create a basic Continuous Integration test
Run a program test at the end.
2024-01-16 21:40:53 -08:00
Aaron Liu
7573de8a61
fix a stupid typo and clarify windows error code 2023-12-06 20:38:24 -05:00
Aaron Liu
c4e12b539a
bump version 2023-12-06 16:04:41 -05:00
Aaron Liu
e5c4677542
Merge branch 'master' of https://github.com/stefanhaustein/TerminalImageViewer 2023-12-06 15:58:41 -05:00
Aaron Liu
11d82bde63
try to help #132
also added a bit of docs
2023-12-06 15:57:55 -05:00
Aaron Liu
c87dd19ea1
should fix #132 2023-12-06 15:49:06 -05:00
Aaron Liu
c11b449672
Merge pull request #131 from Huell-Howitzer/patch-1 2023-11-30 20:34:20 -05:00
Huell-Howitzer
55e6f062a3
Fix typo 2023-11-30 16:45:52 -08:00
Tim Stewart
c29bdc7645 fix typo 2023-10-04 10:47:45 +02:00
Aaron Liu
f0118c7c05
reorder VS and IntelliJ stuff 2023-09-29 21:16:54 -04:00
Aaron Liu
1edd7b0f7f
Update README.md
i didn't mean to be mean-spirited
2023-09-29 21:15:24 -04:00
Aaron Liu
413a90124c
version 1.2 2023-09-29 21:06:50 -04:00
Aaron Liu
aa634424d6
Merge pull request #126 from hialmar/patch-1 concat bug
The code misses a + sign on line 36.
2023-02-16 15:33:53 -05:00
Patrice Torguet
31b959cc49
Correct a small bug
The code misses a + sign on line 36.
2023-02-16 16:17:24 +01:00
Aaron Liu
e769d2239d
Make screenshots textarea for easier uploading 2022-12-25 15:19:10 -05:00
Aaron Liu
6a7354b8fd
Update README.md
Add Homebrew option for imagemagick and add syntax highlighting
2022-07-30 10:30:35 -04:00
Aaron Liu
701237fc5e Delete tiv.rb
Refer to homebrew-core instead.
2022-07-30 10:23:12 -04:00
Aaron Liu
c0ae9cffe0
Update tiv.cpp 2022-06-26 10:38:44 +08:00
Aaron Liu
324eba20d3
Merge pull request #123 from aaronliu0130/bugreport
Add link to discussions as question template
2022-06-26 10:34:55 +08:00
Aaron Liu
859959afc4
Fix some grammar 2022-06-26 10:23:17 +08:00
Aaron Liu
e21a6c76a8
Update config.yml 2022-06-26 10:16:27 +08:00
Aaron Liu
b425e06f40
Delete question.md 2022-06-26 10:15:28 +08:00
Aaron Liu
f54038259b
Update config.yml 2022-06-26 10:15:13 +08:00
Stefan Haustein
8ddd2d74d1
Update issue templates
Remove questions template, as we have added the discussions option
2022-06-25 19:25:30 +02:00
Aaron Liu
e885a15231
Merge pull request #118 from aaronliu0130/bugreport
Move bug and enhancement templates to issue forms
2022-04-15 22:31:08 +08:00
Aaron Liu
6c2596c058 Move bug and enhancement templates to issue forms
This is a combination of 13 commits. Squashed commit messages are as follows:

WIP
Update bug_report.yml
Update bug_report.yml
Update bug_report.yml
Update bug_report.yml
Update bug_report.yml
Update bug_report.yml
Update bug_report.yml
Update bug_report.yml
Update bug_report.yml
Update bug_report.yml
Update and rename feature_request.md to feature_request.yml
Update bug_report.yml
2022-04-09 04:05:12 +00:00
Aaron Liu
5c6198f7dc
Update README.md
stop going back in time and add some spaces
2022-03-29 09:31:21 +08:00
Stefan Haustein
eeab06b2bd
Update README.md 2022-02-13 12:52:02 +01:00
Aaron Liu
6415891683
Update terminalimageviewer.rb 2022-02-04 22:05:29 +08:00
Aaron Liu
1b89356729 Update brew and snap 2022-02-02 21:38:04 +08:00
Aaron Liu
9004bb3f47
Update tiv.rb
Bumped version, added `license`, `branch`, better `install`, and better `test`.
2022-01-31 16:23:39 +08:00
22 changed files with 24231 additions and 16301 deletions

View file

@ -1,32 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
<!--A clear and concise description of what the bug is.-->
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
<!--A clear and concise description of what you expected to happen.-->
**Screenshots**
<!--If applicable, add screenshots to help explain your problem.-->
**OS Information**
Commit(optional):
OS specifics:
**Additional context**
<!--Add any other context about the problem here.-->

42
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View file

@ -0,0 +1,42 @@
name: Bug report
description: Create a report to help us improve
labels: bug
body:
- type: textarea
attributes:
label: Describe the Bug
description: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
attributes:
label: To Reproduce
description: Steps to reproduce the behavio(u)r
value: |-
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
validations:
required: true
- type: textarea
attributes:
label: Expected Behavio(u)r
description: A clear and concise description of what you expected to happen.
validations:
required: true
- type: textarea
attributes:
label: Screenshots
description: If applicable, add screenshots to help explain your problem.
- type: input
attributes:
label: Version/Commit Hash
validations:
required: true
- type: input
attributes:
label: OS Specifics
description: Output of `uname -a` or the Windows build number
validations:
required: true

View file

@ -1 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: "Question"
url: https://github.com/stefanhaustein/TerminalImageViewer/discussions/new?category=q-a
about: Ask things about the project

View file

@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: feature request
assignees: ''
---
**Is your feature request related to a problem? Please describe.(Optional)**
<!--A clear and concise description of what the problem is. -->
**Describe the solution you'd like**
<!--A clear and concise description of what you want to happen.-->
**Describe alternatives you've considered**
<!--A clear and concise description of any alternative solutions or features you've considered.-->
**Additional context**
<!--Add any other context or screenshots about the feature request here.-->

View file

@ -0,0 +1,24 @@
name: Feature request
description: Suggest an idea for this project
labels: feature request
body:
- type: textarea
attributes:
label: Is your feature request related to a problem? Please describe.
description: A clear and concise description of what the bug is.
- type: textarea
attributes:
label: Describe the solution you'd like
description: A clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
attributes:
label: Describe alternatives you've considered
description: A clear and concise description of any alternative solutions or features you've considered.
validations:
required: true
- type: textarea
attributes:
label: Additional context
description: Add any other context or screenshots about the feature request here.

View file

@ -1,8 +0,0 @@
---
name: Question
about: Asks things about the project
title: ''
labels: question
assignees: ''
---

View file

@ -2,7 +2,7 @@
<!--Closes #0-->
<!--(if any, change the zero above to the issue number and uncomment lines 1 and 2)-->
### How can we test this? Step by step instructions please.
### How can we test this? Step-by-step instructions, please.
1.
2.

35
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,35 @@
name: Build and run
on:
workflow_dispatch:
push:
branches: [ "master" ]
paths: ['src/**']
pull_request:
paths: ['src/**']
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install dependencies
run: sudo apt-get install -qy imagemagick
- name: Validate gcc version
run: |
if [[ $(gcc --version | awk '/gcc/ && ($3+0)>13{print "gcc-13+"}') != "gcc-13+" ]]; then
# Script courtesy of https://stackoverflow.com/a/67791068/16134571
sudo apt install gcc-13 g++-13
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-13 100 --slave /usr/bin/g++ g++ /usr/bin/g++-13 --slave /usr/bin/gcov gcov /usr/bin/gcov-13
sudo update-alternatives --set gcc /usr/bin/gcc-13
fi
- name: Build
run: make -C src
- name: Test
run: |
images=('/usr/local/share/icons/hicolor/128x128/apps/microsoft-edge.png' '/usr/local/share/icons/hicolor/128x128/apps/CMakeSetup.png' '/usr/local/doc/cmake/html/_static/file.png' '/usr/local/lib/android/sdk/extras/google/google_play_services/samples/tagmanager/cuteanimals/res/drawable/cat_1.jpg' '/usr/local/lib/android/sdk/extras/google/google_play_services/samples/wallet/res/drawable-ldpi/icon.png' '/usr/local/lib/android/sdk/extras/google/google_play_services/samples/wallet/res/drawable-hdpi/icon.png' '/usr/share/plymouth/themes/spinner/watermark.png' '/usr/share/apache2/icons/apache_pb.png' '/usr/share/doc/libpng-dev/examples/pngtest.png')
image=${images[ $RANDOM % ${#images[@]} ]} # Get random image
./src/tiv -w 160 -h 48 $image # Get random image
echo $image
./src/tiv -w 160 -h 48 /usr/share/pixmaps # Dir mode

43
.github/workflows/cimg.yml vendored Normal file
View file

@ -0,0 +1,43 @@
name: Update CImg
on:
schedule:
- cron: 0 0 3 * * # The first day after this workflow was merged
release:
types: [published]
workflow_dispatch:
jobs:
check-version:
name: Check for updates
runs-on: ubuntu-latest
outputs:
latest-tag: ${{ steps.latest-tag.outputs.result }}
steps:
- name: Fetch the latest tag (could be buggy)
uses: actions/github-script@v7
id: latest-tag
with:
result-encoding: string
script: |
return (await github.rest.repos.listTags({ owner: 'GreycLab', repo: 'CImg', per_page: 28 })).data[27].name
pull-file:
name: Update CImg.h
runs-on: ubuntu-latest
needs: check-version
if: ${{ needs.check-version.outputs.latest-tag != 'v.3.3.6' }}
steps:
- uses: actions/checkout@v2
name: Checkout this repository
with:
token: ${{ secrets.CIMG_UPDATE_TOKEN }}
- name: Download new CImg version
uses: carlosperate/download-file-action@v2
with:
file-url: 'https://github.com/GreycLab/CImg/raw/${{ needs.check-version.outputs.latest-tag }}/CImg.h'
location: 'src'
- name: Commit new CImg version (and update script)
run: |
sed -i 's/v.3.3.6/${{ needs.check-version.outputs.latest-tag }}/' .github/workflows/cimg.yml
git config user.name 'GitHub Actions'
git config user.email 'actions@github.com'
git commit -am "Update CImg to ${{ needs.check-version.outputs.latest-tag }}"
git push

24
.gitignore vendored
View file

@ -35,6 +35,22 @@
tiv
###Visual Studio###
.vs/
*.pdb
*.idb
*.ilk
x64/
*.sln
*.vcxproj
*.vcxproj.*
###Visual Studio Code###
.vscode/
###Java###
# Compiled class file
@ -60,6 +76,9 @@ tiv
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# Intellij
.idea/
*.iml
###Linux###
@ -78,7 +97,6 @@ hs_err_pid*
# Icon must end with two \r
Icon
# Thumbnails
._*
@ -93,10 +111,6 @@ Network Trash Folder
Temporary Items
.apdisk
# Intellij
.idea/
*.iml
###Snap###

212
LICENSE
View file

@ -1,201 +1,19 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2024 Stefan Haustein and Aaron Liu
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
This program is free software: you may copy, redistribute and/or modify it
under the terms of (at your option) either the Apache License, Version 2.0,
or the GNU General Public License as published by the Free Software Foundation,
version 3, or any later version.
1. Definitions.
This file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
For details, see either
<https://www.apache.org/licenses/LICENSE-20> for the Apache License, Version 2.0,
or <https://www.gnu.org/licenses/gpl-3.0.en.html> for the GNU GPL, version 3.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Note that the code contained in this package contains the CImg library,
which is licensed under either [CeCILL 2.0](https://spdx.org/licenses/CECILL-2.0.html)
(close to GPL and compatible with it) or [CeCILL-C](https://spdx.org/licenses/CECILL-C)
(close to LGPL and compatible with Apache).

167
README.md
View file

@ -2,96 +2,127 @@
Small C++ program to display images in a (modern) terminal using RGB ANSI codes and unicode block graphic characters.
There are various similar tools (such as `timg`) using the unicode half block character to display two 24bit pixels per character cell. This program enhances the resolution by mapping 4x8 pixel cells to different unicode characters, using the following algorithm:
For each 4x8 pixel cell of the (potentially downscaled) image:
There are various similar tools (such as `timg`) that use the unicode half block character to display two 24bit pixels per character cell. This program enhances the resolution by mapping 4x8 pixel cells to different unicode characters, using the following algorithm for each 4x8 pixel cell of the (potentially downscaled) image:
1. Find the color channel (R, G or B) that has the biggest range of values for the current cell
2. Split this range in the middle and create a corresponding bitmap for the cell
4. Compare the bitmap to the assumed bitmaps for various unicode block graphics characters
5. Re-calculate the foreground and background colors for the chosen character.
3. Compare the bitmap to the assumed bitmaps for various unicode block graphics characters
4. Re-calculate the foreground and background colors for the chosen character.
See the difference by disabling this optimization using the `-0` option. Or just take a look at the comparison image at the end of this text.
## News
- 2019-03-26: Exciting week: @Cableo has fixed output redirection, @boretom has added cross-compilation support to the build file and @AlanDeSmet has fixed tall thumbnails and greyscale images.
- 2019-01-14: Install via snap: `sudo snap install --edge tiv`
- 2020-04-09: @aaronliu0130 has added homebrew support.
- 2020-07-05: @cxwx has fixed homebrew support.
- 2021-05-21: @aaronliu0130 has added Apple Clang support.
## Installation
### Build from source (Linux)
sudo apt install imagemagick || yum install ImageMagick
git clone https://github.com/stefanhaustein/TerminalImageViewer.git
cd TerminalImageViewer/src/main/cpp
make
sudo make install
### Homebrew (MacOS)
Option 1:
```
brew tap stefanhaustein/TerminalImageViewer https://github.com/stefanhaustein/TerminalImageViewer
brew install tiv
```
Option 2(deprecated, for macOS Mojave and below):
```
brew tap stefanhaustein/TerminalImageViewer https://github.com/stefanhaustein/TerminalImageViewer
brew install terminalimageviewer
```
Option 3(deprecated):
```
brew install https://raw.githubusercontent.com/stefanhaustein/TerminalImageViewer/master/terminalimageviewer.rb
```
### Snap (outdated)
sudo snap install --edge tiv
## Usage
tiv [options] <filename(s)>
```sh
tiv [options] <filename> [<filename>...]
```
The shell will expand wildcards. By default, thumbnails and file names will be displayed if more than one image is provided. To display a list of options, just run the command without any parameters.
The shell will expand wildcards. By default, thumbnails and file names will be displayed if more than one image is provided. For a list of options, run the command without any parameters or with `--help`.
## Packages / Contributions
## News
- megamaced has created a RPM for SUSE:
https://build.opensuse.org/package/show/home:megamaced/terminalimageviewer
- bperel has created a Docker image:
https://hub.docker.com/r/bperel/terminalimageviewer
- teresaejunior has created a snapcraft.yaml file, which can build a Snap package with `sudo docker run -it --rm -v "$PWD:$PWD" -w "$PWD" snapcore/snapcraft sh -c 'apt-get update && snapcraft'`, and then installed with `sudo snap install --dangerous ./*.snap`.
- aaronliu0130 has added brew support.
- 2024-03-20: Added a section on how to use the API.
- 2024-02-01: We are currently working on splitting the source code into dependency-free library files and a client that uses CImg.
- 2023-09-29: Today marks the 40th anniversary of the GNU project. If you haven't learned the news concerning it and Stallman, please do.
Support for MSVC has been added and the repository is now under an Apache 2.0 or GPL3 dual license. CI building for each release will hopefully be setup soon. The main program has also adopted a mostly Google code-style because I (aaron) think it simply makes sense.
`SPDX-License-Identifier: Apache-2.0 OR GPL-3.0-or-later`
- 2021-05-22: We now support Apple Clang, thanks to the C++ filesystem library being no longer experimental. Issue forms have also been added to the GitHub repository.
- 2020-10-22: The Java version is now **deprecated**. Development has long shifted to the C++ version since that was created, and the last meaningful update to it was in 2016.
I am happy to accept useful contributions under the Apache 2.0 licencse, but...
## Installation
- Before investing in larger contributions, please use an issue to discuss this
- Pull requests should be as "atomic" as possible. I won't accept any pull request doing multiple things at once.
- This library currently only depends on ImageMagic as an image processing library and I'd prefer to keep it that way.
- Support for additional platforms, CPUs or similar will require somebody who is happy to help with maintenance, in particular, if I don't have access to it.
> [!IMPORTANT]
> All installation methods require installing ImageMagick, a required dependency. Most package managers should install it automatically.
## Common problems
### All platforms: Build from source
Our makefile currently only supports `g++`. It should be possible to compile `tiv` manually using any of your favorite compilers that support C++17 and Unix headers (`ioctl.h` and `sysexits.h`, specifically) or `windows.h`. PRs are welcome.
```sh
git clone https://github.com/stefanhaustein/TerminalImageViewer.git
cd TerminalImageViewer/src
make
# To move the tiv binary into your PATH (hopefully), also do
sudo make install
```
Please don't forget to install ImageMagick... On Debian based Linux via `sudo apt install imagemagick` and
on MacOS via `brew install imagemagick`.
### Mac: Homebrew
```sh
brew install tiv
```
As the original Apple Shell only supports 256 color mode (-256) and there seems to be some extra
line spacing, distorting the image, we also recommend installing iTerm2:
```
brew install --cask iterm2
```
### Third-Party Packages
- @megamaced has created [an RPM for SUSE](https://build.opensuse.org/package/show/home:megamaced/terminalimageviewer)
- @bperel has created [a Docker image](https://hub.docker.com/r/bperel/terminalimageviewer)
## Common problems / Troubleshooting
- Errors such as "unrecognized file format"? Make sure ImageMagic is installed.
- On some linux platforms, an extra flag seems to be required: `make LDLIBS=-lstdc++fs` (but it also breaks MacOs), see <https://github.com/stefanhaustein/TerminalImageViewer/issues/103>
- If you see strange horizontal lines, the characters don't fully fill the character cell. Remove additional line spacing in your terminal app
- Wrong colors? Try -256 to use a 256 color palette instead of 24 bit colors
- Strange characters? Try -0 or install an use full unicode font (e.g. inconsolata or firacode)
## Using the TIV API
Tiv can be used as an API. So if you always wanted to run your favorite FPS in a shell, this is the opportunity.
All the code useful as a library is isolated in [tiv_lib.h](https://github.com/stefanhaustein/TerminalImageViewer/blob/master/src/tiv_lib.h)
and [tiv_lib.cc](https://github.com/stefanhaustein/TerminalImageViewer/blob/master/src/tiv_lib.cc).
The main entry point is
```cpp
CharData findCharData(GetPixelFunction get_pixel, int x0, int y0, const int &flags)
```
The call takes a std::Function that allows the TIV code to request pixels from your framebuffer.
From this framebuffer, the call will query pixels for a 4x8 pixel rectangle, where x0 and y0
define the top left corner. The call searches the best unicode graphics character and colors to approximate this
cell of the image, and returns these in a CharData struct.
## Contributions
- 2019-03-26: Exciting week: @cabelo has fixed output redirection, @boretom has added cross-compilation support to the build file and @AlanDeSmet has fixed tall thumbnails and greyscale images.
- 2020-07-05: @cxwx has fixed homebrew support.
I am happy to accept useful contributions under the Apache 2.0 license, but...
- Before investing in larger contributions, please use an issue to discuss this
- Pull requests should be as "atomic" as possible. I won't accept any pull request doing multiple things at once.
- This program currently only depends on CImg and ImageMagick as image processing libraries and I'd prefer to keep it that way.
- Support for additional platforms, CPUs or similar will require somebody who is happy to help with maintenance, in particular if I don't have access to it.
- On some linux platforms, an extra flag seems to be required: `make LDLIBS=-lstdc++fs` (but it also breaks MacOs), see https://github.com/stefanhaustein/TerminalImageViewer/issues/103
- If you see strange horizontal lines, the characters don't fully fill the character cell. Remove additional line spacing in your terminal app
- Wrong colors? Try -256 to use a 256 color palette instead of 24 bit colors
- Strange characters? Try -0 or install an use full unicode font (e.g. inconsolata or firacode)
## Examples
![Examples](https://i.imgur.com/8UyGjg8.png)
Most examples were shot with the Java version of this program, which should have equivalent output but slower by millenia in CPU years.
![Examples](https://i.imgur.com/yWRZ3yk.png)
If multiple images match the filename spec, thumbnails are shown.
![Thumbnails](https://i.imgur.com/PTYgSqz.png)
## Comparison to Using Half-Block Characters Only
The top image was generated with the character optimization disabled via the `-0` option.
For the example below, the top image was generated with the character optimization disabled via the `-0` option.
![Comparison](https://i.imgur.com/OzdCeh6.png)
## Licensing
You are free to use this code under either the GPL (3 or later) or version 2.0 of the Apache license. We include the CImg library, which
is licensed under either [CeCILL 2.0](https://spdx.org/licenses/CECILL-2.0.html) (close to GPL and compatible with it) or [CeCILL-C] (https://spdx.org/licenses/CECILL-C) (close to LGPL and compatible with Apache).

View file

@ -1,5 +1,5 @@
name: tiv
version: "v1.0.0"
version: "v1.1.1"
summary: Terminal Image Viewer
description: |
tiv is a small C++ program to display images in a (modern) terminal using
@ -17,7 +17,7 @@ parts:
tiv:
plugin: make
source-type: tar
source: https://github.com/stefanhaustein/TerminalImageViewer/archive/v1.0.0.tar.gz
source: https://github.com/stefanhaustein/TerminalImageViewer/archive/v1.1.1.tar.gz
source-subdir: src/main/cpp
build-packages:
- g++
@ -29,7 +29,7 @@ parts:
install $SNAPCRAFT_PART_BUILD/tiv $SNAPCRAFT_PART_INSTALL/usr/bin/
imagemagick:
plugin: autotools
source: https://www.imagemagick.org/download/releases/ImageMagick-7.0.7-39.tar.xz
source: https://www.imagemagick.org/download/releases/ImageMagick-7.1.0-22.tar.xz
source-type: tar
configflags:
- --enable-hdri=yes

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
PROGNAME = tiv
OBJECTS = tiv.o
OBJECTS = tiv.o tiv_lib.o
CXX ?= g++
CXXFLAGS ?= -O2 -fpermissive
INSTALL ?= install
@ -17,7 +17,9 @@ override LDFLAGS += -pthread
all: $(PROGNAME)
tiv.o: CImg.h
tiv_lib.o: tiv_lib.h
tiv.o: CImg.h tiv_lib.h
$(PROGNAME): $(OBJECTS)
$(CXX) $(LDFLAGS) $^ -o $@ $(LOADLIBES) $(LDLIBS)

View file

@ -33,8 +33,8 @@ public class TerminalImageViewer {
"TerminalImageViewer Java\n" +
" - Use -w and -h to set the maximum width and height in characters (defaults: 80, 24).\n" +
" - Use -256 for 256 color mode, -grayscale for grayscale and -stdin to obtain file names from stdin.\n" +
" - When multiple files are supplied, -c sets the number of images per row (default: 4)."
"NOTE: This version of TerminalImageViewer is not regularly updated. Please use the C++ version instead.\n");
" - When multiple files are supplied, -c sets the number of images per row (default: 4)." +
"NOTE: This version of TerminalImageViewer is deprecated. Please use the C++ version instead.\n");
return;
}

View file

@ -1,648 +0,0 @@
#include <iostream>
#include <bitset>
#include <cmath>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <array>
#include <sys/ioctl.h>
#include <filesystem>
#define cimg_display 0
#include "CImg.h"
//using namespace std;
const int FLAG_FG = 1;
const int FLAG_BG = 2;
const int FLAG_MODE_256 = 4;
const int FLAG_24BIT = 8;
const int FLAG_NOOPT = 16;
const int FLAG_TELETEXT = 32;
const int COLOR_STEP_COUNT = 6;
const int COLOR_STEPS[COLOR_STEP_COUNT] = {0, 0x5f, 0x87, 0xaf, 0xd7, 0xff};
const int GRAYSCALE_STEP_COUNT = 24;
const int GRAYSCALE_STEPS[GRAYSCALE_STEP_COUNT] = {
0x08, 0x12, 0x1c, 0x26, 0x30, 0x3a, 0x44, 0x4e, 0x58, 0x62, 0x6c, 0x76,
0x80, 0x8a, 0x94, 0x9e, 0xa8, 0xb2, 0xbc, 0xc6, 0xd0, 0xda, 0xe4, 0xee};
const unsigned int BITMAPS[] = {
0x00000000, 0x00a0,
// Block graphics
// 0xffff0000, 0x2580, // upper 1/2; redundant with inverse lower 1/2
0x0000000f, 0x2581, // lower 1/8
0x000000ff, 0x2582, // lower 1/4
0x00000fff, 0x2583,
0x0000ffff, 0x2584, // lower 1/2
0x000fffff, 0x2585,
0x00ffffff, 0x2586, // lower 3/4
0x0fffffff, 0x2587,
//0xffffffff, 0x2588, // full; redundant with inverse space
0xeeeeeeee, 0x258a, // left 3/4
0xcccccccc, 0x258c, // left 1/2
0x88888888, 0x258e, // left 1/4
0x0000cccc, 0x2596, // quadrant lower left
0x00003333, 0x2597, // quadrant lower right
0xcccc0000, 0x2598, // quadrant upper left
//0xccccffff, 0x2599, // 3/4 redundant with inverse 1/4
0xcccc3333, 0x259a, // diagonal 1/2
//0xffffcccc, 0x259b, // 3/4 redundant
//0xffff3333, 0x259c, // 3/4 redundant
0x33330000, 0x259d, // quadrant upper right
//0x3333cccc, 0x259e, // 3/4 redundant
//0x3333ffff, 0x259f, // 3/4 redundant
// Line drawing subset: no double lines, no complex light lines
0x000ff000, 0x2501, // Heavy horizontal
0x66666666, 0x2503, // Heavy vertical
0x00077666, 0x250f, // Heavy down and right
0x000ee666, 0x2513, // Heavy down and left
0x66677000, 0x2517, // Heavy up and right
0x666ee000, 0x251b, // Heavy up and left
0x66677666, 0x2523, // Heavy vertical and right
0x666ee666, 0x252b, // Heavy vertical and left
0x000ff666, 0x2533, // Heavy down and horizontal
0x666ff000, 0x253b, // Heavy up and horizontal
0x666ff666, 0x254b, // Heavy cross
0x000cc000, 0x2578, // Bold horizontal left
0x00066000, 0x2579, // Bold horizontal up
0x00033000, 0x257a, // Bold horizontal right
0x00066000, 0x257b, // Bold horizontal down
0x06600660, 0x254f, // Heavy double dash vertical
0x000f0000, 0x2500, // Light horizontal
0x0000f000, 0x2500, //
0x44444444, 0x2502, // Light vertical
0x22222222, 0x2502,
0x000e0000, 0x2574, // light left
0x0000e000, 0x2574, // light left
0x44440000, 0x2575, // light up
0x22220000, 0x2575, // light up
0x00030000, 0x2576, // light right
0x00003000, 0x2576, // light right
0x00004444, 0x2577, // light down
0x00002222, 0x2577, // light down
// Misc technical
0x44444444, 0x23a2, // [ extension
0x22222222, 0x23a5, // ] extension
0x0f000000, 0x23ba, // Horizontal scanline 1
0x00f00000, 0x23bb, // Horizontal scanline 3
0x00000f00, 0x23bc, // Horizontal scanline 7
0x000000f0, 0x23bd, // Horizontal scanline 9
// Geometrical shapes. Tricky because some of them are too wide.
//0x00ffff00, 0x25fe, // Black medium small square
0x00066000, 0x25aa, // Black small square
//0x11224488, 0x2571, // diagonals
//0x88442211, 0x2572,
//0x99666699, 0x2573,
//0x000137f0, 0x25e2, // Triangles
//0x0008cef0, 0x25e3,
//0x000fec80, 0x25e4,
//0x000f7310, 0x25e5,
0, 0, // End marker for "regular" characters
// Teletext / legacy graphics 3x2 block character codes.
// Using a 3-2-3 pattern consistently, perhaps we should create automatic variations....
0xccc00000, 0xfb00,
0x33300000, 0xfb01,
0xfff00000, 0xfb02,
0x000cc000, 0xfb03,
0xccccc000, 0xfb04,
0x333cc000, 0xfb05,
0xfffcc000, 0xfb06,
0x00033000, 0xfb07,
0xccc33000, 0xfb08,
0x33333000, 0xfb09,
0xfff33000, 0xfb0a,
0x000ff000, 0xfb0b,
0xcccff000, 0xfb0c,
0x333ff000, 0xfb0d,
0xfffff000, 0xfb0e,
0x00000ccc, 0xfb0f,
0xccc00ccc, 0xfb10,
0x33300ccc, 0xfb11,
0xfff00ccc, 0xfb12,
0x000ccccc, 0xfb13,
0x333ccccc, 0xfb14,
0xfffccccc, 0xfb15,
0x00033ccc, 0xfb16,
0xccc33ccc, 0xfb17,
0x33333ccc, 0xfb18,
0xfff33ccc, 0xfb19,
0x000ffccc, 0xfb1a,
0xcccffccc, 0xfb1b,
0x333ffccc, 0xfb1c,
0xfffffccc, 0xfb1d,
0x00000333, 0xfb1e,
0xccc00333, 0xfb1f,
0x33300333, 0x1b20,
0xfff00333, 0x1b21,
0x000cc333, 0x1b22,
0xccccc333, 0x1b23,
0x333cc333, 0x1b24,
0xfffcc333, 0x1b25,
0x00033333, 0x1b26,
0xccc33333, 0x1b27,
0xfff33333, 0x1b28,
0x000ff333, 0x1b29,
0xcccff333, 0x1b2a,
0x333ff333, 0x1b2b,
0xfffff333, 0x1b2c,
0x00000fff, 0x1b2d,
0xccc00fff, 0x1b2e,
0x33300fff, 0x1b2f,
0xfff00fff, 0x1b30,
0x000ccfff, 0x1b31,
0xcccccfff, 0x1b32,
0x333ccfff, 0x1b33,
0xfffccfff, 0x1b34,
0x00033fff, 0x1b35,
0xccc33fff, 0x1b36,
0x33333fff, 0x1b37,
0xfff33fff, 0x1b38,
0x000fffff, 0x1b39,
0xcccfffff, 0x1b3a,
0x333fffff, 0x1b3b,
0, 1 // End marker for extended TELETEXT mode.
};
struct CharData {
std::array<int, 3> fgColor = std::array<int, 3>{0, 0, 0};
std::array<int, 3> bgColor = std::array<int, 3>{0, 0, 0};
int codePoint;
};
// Return a CharData struct with the given code point and corresponding averag fg and bg colors.
CharData createCharData(const cimg_library::CImg<unsigned char> & image, int x0, int y0, int codepoint, int pattern) {
CharData result;
result.codePoint = codepoint;
int fg_count = 0;
int bg_count = 0;
unsigned int mask = 0x80000000;
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 4; x++) {
int* avg;
if (pattern & mask) {
avg = result.fgColor.data();
fg_count++;
} else {
avg = result.bgColor.data();
bg_count++;
}
for (int i = 0; i < 3; i++) {
avg[i] += image(x0 + x, y0 + y, 0, i);
}
mask = mask >> 1;
}
}
// Calculate the average color value for each bucket
for (int i = 0; i < 3; i++) {
if (bg_count != 0) {
result.bgColor[i] /= bg_count;
}
if (fg_count != 0) {
result.fgColor[i] /= fg_count;
}
}
return result;
}
// Find the best character and colors for a 4x8 part of the image at the given position
CharData findCharData(const cimg_library::CImg<unsigned char> & image, int x0, int y0, int flags) {
int min[3] = {255, 255, 255};
int max[3] = {0};
std::map<long,int> count_per_color;
// Determine the minimum and maximum value for each color channel
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 4; x++) {
long color = 0;
for (int i = 0; i < 3; i++) {
int d = image(x0 + x, y0 + y, 0, i);
min[i] = std::min(min[i], d);
max[i] = std::max(max[i], d);
color = (color << 8) | d;
}
count_per_color[color]++;
}
}
std::multimap<int,long> color_per_count;
for (auto i = count_per_color.begin(); i != count_per_color.end(); ++i) {
color_per_count.insert(std::pair<int,long>(i->second, i->first));
}
auto iter = color_per_count.rbegin();
int count2 = iter->first;
long max_count_color_1 = iter->second;
long max_count_color_2 = max_count_color_1;
if ((++iter) != color_per_count.rend()) {
count2 += iter->first;
max_count_color_2 = iter->second;
}
unsigned int bits = 0;
bool direct = count2 > (8*4) / 2;
if (direct) {
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 4; x++) {
bits = bits << 1;
int d1 = 0;
int d2 = 0;
for (int i = 0; i < 3; i++) {
int shift = 16 - 8 * i;
int c1 = (max_count_color_1 >> shift) & 255;
int c2 = (max_count_color_2 >> shift) & 255;
int c = image(x0 + x, y0 + y, 0, i);
d1 += (c1-c) * (c1-c);
d2 += (c2-c) * (c2-c);
}
if (d1 > d2) {
bits |= 1;
}
}
}
} else {
// Determine the color channel with the greatest range.
int splitIndex = 0;
int bestSplit = 0;
for (int i = 0; i < 3; i++) {
if (max[i] - min[i] > bestSplit) {
bestSplit = max[i] - min[i];
splitIndex = i;
}
}
// We just split at the middle of the interval instead of computing the median.
int splitValue = min[splitIndex] + bestSplit / 2;
// Compute a bitmap using the given split and sum the color values for both buckets.
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 4; x++) {
bits = bits << 1;
if (image(x0 + x, y0 + y, 0, splitIndex) > splitValue) {
bits |= 1;
}
}
}
}
// Find the best bitmap match by counting the bits that don't match,
// including the inverted bitmaps.
int best_diff = 8;
unsigned int best_pattern = 0x0000ffff;
int codepoint = 0x2584;
bool inverted = false;
unsigned int end_marker = flags & FLAG_TELETEXT ? 1 : 0;
for (int i = 0; BITMAPS[i + 1] != end_marker; i += 2) {
// Skip all end markers
if (BITMAPS[i + 1] < 32) {
continue;
}
unsigned int pattern = BITMAPS[i];
for (int j = 0; j < 2; j++) {
int diff = (std::bitset<32>(pattern ^ bits)).count();
if (diff < best_diff) {
best_pattern = BITMAPS[i]; // pattern might be inverted.
codepoint = BITMAPS[i + 1];
best_diff = diff;
inverted = best_pattern != pattern;
}
pattern = ~pattern;
}
}
if (direct) {
CharData result;
if (inverted) {
long tmp = max_count_color_1;
max_count_color_1 = max_count_color_2;
max_count_color_2 = tmp;
}
for (int i = 0; i < 3; i++) {
int shift = 16 - 8 * i;
result.fgColor[i] = (max_count_color_2 >> shift) & 255;
result.bgColor[i] = (max_count_color_1 >> shift) & 255;
result.codePoint = codepoint;
}
return result;
}
return createCharData(image, x0, y0, codepoint, best_pattern);
}
int clamp_byte(int value) {
return value < 0 ? 0 : (value > 255 ? 255 : value);
}
double sqr(double n) {
return n*n;
}
int best_index(int value, const int data[], int count) {
int best_diff = std::abs(data[0] - value);
int result = 0;
for (int i = 1; i < count; i++) {
int diff = std::abs(data[i] - value);
if (diff < best_diff) {
result = i;
best_diff = diff;
}
}
return result;
}
void emit_color(int flags, int r, int g, int b) {
r = clamp_byte(r);
g = clamp_byte(g);
b = clamp_byte(b);
bool bg = (flags & FLAG_BG) != 0;
if ((flags & FLAG_MODE_256) == 0) {
std::cout << (bg ? "\x1b[48;2;" : "\x1b[38;2;") << r << ';' << g << ';' << b << 'm';
return;
}
int ri = best_index(r, COLOR_STEPS, COLOR_STEP_COUNT);
int gi = best_index(g, COLOR_STEPS, COLOR_STEP_COUNT);
int bi = best_index(b, COLOR_STEPS, COLOR_STEP_COUNT);
int rq = COLOR_STEPS[ri];
int gq = COLOR_STEPS[gi];
int bq = COLOR_STEPS[bi];
int gray = static_cast<int>(std::round(r * 0.2989f + g * 0.5870f + b * 0.1140f));
int gri = best_index(gray, GRAYSCALE_STEPS, GRAYSCALE_STEP_COUNT);
int grq = GRAYSCALE_STEPS[gri];
int color_index;
if (0.3 * sqr(rq-r) + 0.59 * sqr(gq-g) + 0.11 * sqr(bq-b) <
0.3 * sqr(grq-r) + 0.59 * sqr(grq-g) + 0.11 * sqr(grq-b)) {
color_index = 16 + 36 * ri + 6 * gi + bi;
} else {
color_index = 232 + gri; // 1..24 -> 232..255
}
std::cout << (bg ? "\x1B[48;5;" : "\u001B[38;5;") << color_index << "m";
}
void emitCodepoint(int codepoint) {
if (codepoint < 128) {
std::cout << (char) codepoint;
} else if (codepoint < 0x7ff) {
std::cout << (char) (0xc0 | (codepoint >> 6));
std::cout << (char) (0x80 | (codepoint & 0x3f));
} else if (codepoint < 0xffff) {
std::cout << (char) (0xe0 | (codepoint >> 12));
std::cout << (char) (0x80 | ((codepoint >> 6) & 0x3f));
std::cout << (char) (0x80 | (codepoint & 0x3f));
} else if (codepoint < 0x10ffff) {
std::cout << (char) (0xf0 | (codepoint >> 18));
std::cout << (char) (0x80 | ((codepoint >> 12) & 0x3f));
std::cout << (char) (0x80 | ((codepoint >> 6) & 0x3f));
std::cout << (char) (0x80 | (codepoint & 0x3f));
} else {
std::cerr << "ERROR";
}
}
void emit_image(const cimg_library::CImg<unsigned char> & image, int flags) {
CharData lastCharData;
for (int y = 0; y <= image.height() - 8; y += 8) {
for (int x = 0; x <= image.width() - 4; x += 4) {
CharData charData = flags & FLAG_NOOPT
? createCharData(image, x, y, 0x2584, 0x0000ffff)
: findCharData(image, x, y, flags);
if (x == 0 || charData.bgColor != lastCharData.bgColor)
emit_color(flags | FLAG_BG, charData.bgColor[0], charData.bgColor[1], charData.bgColor[2]);
if (x == 0 || charData.fgColor != lastCharData.fgColor)
emit_color(flags | FLAG_FG, charData.fgColor[0], charData.fgColor[1], charData.fgColor[2]);
emitCodepoint(charData.codePoint);
lastCharData = charData;
}
std::cout << "\x1b[0m" << std::endl;
}
}
struct size {
size(unsigned int in_width, unsigned int in_height) :
width(in_width), height(in_height) {
}
size(cimg_library::CImg<unsigned int> img) :
width(img.width()), height(img.height()) {
}
unsigned int width;
unsigned int height;
size scaled(double scale) {
return size(width*scale, height*scale);
}
size fitted_within(size container) {
double scale = std::min(container.width / (double) width, container.height / (double) height);
return scaled(scale);
}
};
std::ostream& operator<<(std::ostream& stream, size sz) {
stream << sz.width << "x" << sz.height;
return stream;
}
void emit_usage() {
std::cerr << "Terminal Image Viewer v1.1.0" << std::endl << std::endl;
std::cerr << "usage: tiv [options] <image> [<image>...]" << std::endl << std::endl;
std::cerr << " -0 : No block character adjustment, always use top half block char." << std::endl;
std::cerr << " -256 : Use 256 color mode." << std::endl;
std::cerr << " -c <num> : Number of thumbnail columns in 'dir' mode (3)." << std::endl;
std::cerr << " -d : Force 'dir' mode. Automatially selected for more than one input." << std::endl;
std::cerr << " -f : Force 'full' mode. Automatically selected for one input." << std::endl;
std::cerr << " -help : Display this help text." << std::endl;
std::cerr << " -h <num> : Set the maximum height to <num> lines." << std::endl;
std::cerr << " -w <num> : Set the maximum width to <num> characters." << std::endl;
std::cerr << " -x : Use new Unicode Teletext/legacy charactery (experimental)." << std::endl << std::endl;
}
enum Mode {AUTO, THUMBNAILS, FULL_SIZE};
/* Wrapper around CImg<T>(const char*) to ensure the result has 3 channels as RGB
*/
cimg_library::CImg<unsigned char> load_rgb_CImg(const char * const filename) {
cimg_library::CImg<unsigned char> image(filename);
if(image.spectrum() == 1) {
// Greyscale. Just copy greyscale data to all channels
cimg_library::CImg<unsigned char> rgb_image(image.width(), image.height(), image.depth(), 3);
for(unsigned int chn = 0; chn < 3; chn++) {
rgb_image.draw_image(0, 0, 0,chn, image);
}
return rgb_image;
}
return image;
}
int main(int argc, char* argv[]) {
int maxWidth = 80;
int maxHeight = 24;
bool sizeDetectionSuccessful = true;
struct winsize w;
int ioStatus = ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
// If redirecting STDOUT to one file ( col or row == 0, or the previous ioctl call's failed )
if (ioStatus != 0 || (w.ws_col | w.ws_row) == 0) {
ioStatus = ioctl(STDIN_FILENO, TIOCGWINSZ, &w);
if (ioStatus != 0 || (w.ws_col | w.ws_row) == 0) {
std::cerr << "Warning: failed to determine most reasonable size, defaulting to 80x24" << std::endl;
sizeDetectionSuccessful = false;
}
}
if (sizeDetectionSuccessful)
{
maxWidth = w.ws_col * 4;
maxHeight = w.ws_row * 8;
}
int flags = 0;
Mode mode = AUTO;
int columns = 3;
std::vector<std::string> file_names;
int error = 0;
if (argc <= 1) {
emit_usage();
return 0;
}
for (int i = 1; i < argc; i++) {
std::string arg(argv[i]);
if (arg == "-0") {
flags |= FLAG_NOOPT;
} else if (arg == "-c") {
if (i < argc - 1)
columns = std::stoi(argv[++i]);
} else if (arg == "-d") {
mode = THUMBNAILS;
} else if (arg == "-f") {
mode = FULL_SIZE;
} else if (arg == "-w") {
if (i < argc - 1)
maxWidth = 4 * std::stoi(argv[++i]);
} else if (arg == "-h") {
if (i < argc - 1)
maxHeight = 8 * std::stoi(argv[++i]);
} else if (arg == "-256") {
flags |= FLAG_MODE_256;
} else if (arg == "--help" || arg == "-help") {
emit_usage();
} else if (arg == "-x") {
flags |= FLAG_TELETEXT;
} else if (arg[0] == '-') {
std::cerr << "Unrecognized argument: " << arg << std::endl;
} else {
if (std::filesystem::is_directory(arg)) {
for (auto & p : std::filesystem::directory_iterator(arg)) {
if (std::filesystem::is_regular_file(p.path())) {
file_names.push_back(p.path().string());
}
}
} else {
std::ifstream fin(arg.c_str());
if (fin) {
file_names.push_back(arg);
} else {
std::cerr << "Can't open file (permission?): " << arg << std::endl;
}
}
}
}
if (mode == FULL_SIZE || (mode == AUTO && file_names.size() == 1)) {
for (unsigned int i = 0; i < file_names.size(); i++) {
try {
cimg_library::CImg<unsigned char> image = load_rgb_CImg(file_names[i].c_str());
if (image.width() > maxWidth || image.height() > maxHeight) {
size new_size = size(image).fitted_within(size(maxWidth,maxHeight));
image.resize(new_size.width, new_size.height, -100, -100, 5);
}
emit_image(image, flags);
} catch(cimg_library::CImgIOException & e) {
error = 1;
std::cerr << "File format is not recognized for '" << file_names[i] << "'" << std::endl;
}
}
} else {
// Thumbnail mode
unsigned int index = 0;
int cw = (((maxWidth / 4) - 2 * (columns - 1)) / columns);
int tw = cw * 4;
cimg_library::CImg<unsigned char> image(tw * columns + 2 * 4 * (columns - 1), tw, 1, 3);
size maxThumbSize(tw, tw);
while (index < file_names.size()) {
image.fill(0);
int count = 0;
std::string sb;
while (index < file_names.size() && count < columns) {
std::string name = file_names[index++];
try {
cimg_library::CImg<unsigned char> original = load_rgb_CImg(name.c_str());
auto cut = name.find_last_of("/");
sb += cut == std::string::npos ? name : name.substr(cut + 1);
size newSize = size(original).fitted_within(maxThumbSize);
original.resize(newSize.width, newSize.height, 1, -100, 5);
image.draw_image(count * (tw + 8) + (tw - newSize.width) / 2, (tw - newSize.height) / 2, 0, 0, original);
count++;
unsigned int sl = count * (cw + 2);
sb.resize(sl - 2, ' ');
sb += " ";
} catch (std::exception & e) {
// Probably no image; ignore.
}
}
if (count) emit_image(image, flags);
std::cout << sb << std::endl << std::endl;
}
}
return error;
}

383
src/tiv.cpp Normal file
View file

@ -0,0 +1,383 @@
/*
* Copyright (c) 2017-2023, Stefan Haustein, Aaron Liu
*
* This file is free software: you may copy, redistribute and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* Alternatively, you may copy, redistribute and/or modify this file under
* the terms of the Apache License, version 2.0:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <array>
#include <bitset>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "tiv_lib.h"
// This #define tells CImg that we use the library without any display options
// -- just for loading images.
#define cimg_display 0
#include "CImg.h"
#ifdef _POSIX_VERSION
// Console output size detection
#include <sys/ioctl.h>
// Error explanation, for some reason
#include <cstring>
#endif
#ifdef _WIN32
#include <windows.h>
// Error explanation
#include <system_error>
#endif
// Program exit code constants compatible with sysexits.h.
#define EXITCODE_OK 0
#define EXITCODE_COMMAND_LINE_USAGE_ERROR 64
#define EXITCODE_DATA_FORMAT_ERROR 65
#define EXITCODE_NO_INPUT_ERROR 66
void printTermColor(const int &flags, int r, int g, int b) {
r = clamp_byte(r);
g = clamp_byte(g);
b = clamp_byte(b);
bool bg = (flags & FLAG_BG) != 0;
if ((flags & FLAG_MODE_256) == 0) {
std::cout << (bg ? "\x1b[48;2;" : "\x1b[38;2;") << r << ';' << g << ';'
<< b << 'm';
return;
}
int ri = best_index(r, COLOR_STEPS, COLOR_STEP_COUNT);
int gi = best_index(g, COLOR_STEPS, COLOR_STEP_COUNT);
int bi = best_index(b, COLOR_STEPS, COLOR_STEP_COUNT);
int rq = COLOR_STEPS[ri];
int gq = COLOR_STEPS[gi];
int bq = COLOR_STEPS[bi];
int gray =
static_cast<int>(std::round(r * 0.2989f + g * 0.5870f + b * 0.1140f));
int gri = best_index(gray, GRAYSCALE_STEPS, GRAYSCALE_STEP_COUNT);
int grq = GRAYSCALE_STEPS[gri];
int color_index;
if (0.3 * sqr(rq - r) + 0.59 * sqr(gq - g) + 0.11 * sqr(bq - b) <
0.3 * sqr(grq - r) + 0.59 * sqr(grq - g) + 0.11 * sqr(grq - b)) {
color_index = 16 + 36 * ri + 6 * gi + bi;
} else {
color_index = 232 + gri; // 1..24 -> 232..255
}
std::cout << (bg ? "\x1B[48;5;" : "\u001B[38;5;") << color_index << "m";
}
void printCodepoint(int codepoint) {
if (codepoint < 128) {
std::cout << static_cast<char>(codepoint);
} else if (codepoint < 0x7ff) {
std::cout << static_cast<char>(0xc0 | (codepoint >> 6));
std::cout << static_cast<char>(0x80 | (codepoint & 0x3f));
} else if (codepoint < 0xffff) {
std::cout << static_cast<char>(0xe0 | (codepoint >> 12));
std::cout << static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f));
std::cout << static_cast<char>(0x80 | (codepoint & 0x3f));
} else if (codepoint < 0x10ffff) {
std::cout << static_cast<char>(0xf0 | (codepoint >> 18));
std::cout << static_cast<char>(0x80 | ((codepoint >> 12) & 0x3f));
std::cout << static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f));
std::cout << static_cast<char>(0x80 | (codepoint & 0x3f));
} else {
std::cerr << "ERROR";
}
}
void printImage(const cimg_library::CImg<unsigned char> &image,
const int &flags) {
GetPixelFunction get_pixel = [&](int x, int y) -> unsigned long {
return (((unsigned long) image(x, y, 0, 0)) << 16)
| (((unsigned long) image(x, y, 0, 1)) << 8)
| (((unsigned long) image(x, y, 0, 2)));
};
CharData lastCharData;
for (int y = 0; y <= image.height() - 8; y += 8) {
for (int x = 0; x <= image.width() - 4; x += 4) {
CharData charData =
flags & FLAG_NOOPT
? createCharData(get_pixel, x, y, 0x2584, 0x0000ffff)
: findCharData(get_pixel, x, y, flags);
if (x == 0 || charData.bgColor != lastCharData.bgColor)
printTermColor(flags | FLAG_BG, charData.bgColor[0],
charData.bgColor[1], charData.bgColor[2]);
if (x == 0 || charData.fgColor != lastCharData.fgColor)
printTermColor(flags | FLAG_FG, charData.fgColor[0],
charData.fgColor[1], charData.fgColor[2]);
printCodepoint(charData.codePoint);
lastCharData = charData;
}
std::cout << "\x1b[0m" << std::endl;
}
}
struct size {
size(unsigned int in_width, unsigned int in_height)
: width(in_width), height(in_height) {}
explicit size(cimg_library::CImg<unsigned int> img)
: width(img.width()), height(img.height()) {}
unsigned int width;
unsigned int height;
size scaled(double scale) { return size(width * scale, height * scale); }
size fitted_within(size container) {
double scale = std::min(container.width / static_cast<double>(width),
container.height / static_cast<double>(height));
return scaled(scale);
}
};
std::ostream &operator<<(std::ostream &stream, size sz) {
stream << sz.width << "x" << sz.height;
return stream;
}
/**
* @brief Wrapper around CImg<T>(const char*) constructor
* that always returns a CImg image with 3 channels (RGB)
*
* @param filename The file to construct a CImg object on
* @return cimg_library::CImg<unsigned char> Constructed CImg RGB image
*/
cimg_library::CImg<unsigned char> load_rgb_CImg(const char *const &filename) {
cimg_library::CImg<unsigned char> image(filename);
if (image.spectrum() == 1) {
// Greyscale. Just copy greyscale data to all channels
cimg_library::CImg<unsigned char> rgb_image(
image.width(), image.height(), image.depth(), 3);
for (unsigned int chn = 0; chn < 3; chn++) {
rgb_image.draw_image(0, 0, 0, chn, image);
}
return rgb_image;
}
return image;
}
// Implements --help
void printUsage() {
std::cerr << R"(
Terminal Image Viewer v1.2.1
usage: tiv [options] <image> [<image>...]
-0 : No block character adjustment, always use top half block char.
-2, --256 : Use 256-bit colors. Needed to display properly on macOS Terminal.
-c <num> : Number of thumbnail columns in 'dir' mode (3 by default).
-d, --dir : Force 'dir' mode. Automatically selected for more than one input.
-f, --full: Force 'full' mode. Automatically selected for one input.
--help : Display this help text.
-h <num> : Set the maximum output height to <num> lines.
-w <num> : Set the maximum output width to <num> characters.
-x : Use new Unicode Teletext/legacy characters (experimental).)"
<< std::endl;
}
enum Mode { AUTO, THUMBNAILS, FULL_SIZE };
int main(int argc, char *argv[]) {
std::ios::sync_with_stdio(false); // apparently makes printing faster
bool detectSize = true;
// Platform-specific implementations for determining console size, better
// implementations are welcome Fallback sizes when unsuccessful
int maxWidth = 80;
int maxHeight = 24;
// Reading input
char flags = 0; // bitwise representation of flags,
// see https://stackoverflow.com/a/14295472
Mode mode = AUTO; // either THUMBNAIL or FULL_SIZE
int columns = 3;
std::vector<std::string> file_names;
int ret = EXITCODE_OK; // The return code for the program
if (argc <= 1) {
printUsage();
return EXITCODE_COMMAND_LINE_USAGE_ERROR;
}
for (int i = 1; i < argc; i++) {
std::string arg(argv[i]);
if (arg == "-0") {
flags |= FLAG_NOOPT;
} else if (arg == "-c") {
if (i < argc - 1) {
columns = std::stoi(argv[++i]);
} else {
std::cerr << "Error: -c requires a number" << std::endl;
ret = EXITCODE_COMMAND_LINE_USAGE_ERROR;
}
} else if (arg == "-d" || arg == "--dir") {
mode = THUMBNAILS;
} else if (arg == "-f" || arg == "--full") {
mode = FULL_SIZE;
} else if (arg == "-w") {
if (i < argc - 1) {
maxWidth = 4 * std::stoi(argv[++i]), detectSize = false;
} else {
std::cerr << "Error: -w requires a number" << std::endl;
ret = EXITCODE_COMMAND_LINE_USAGE_ERROR;
}
} else if (arg == "-h") {
if (i < argc - 1)
maxHeight = 8 * std::stoi(argv[++i]), detectSize = false;
else
printUsage(); // people might confuse this with help
} else if (arg == "--256" || arg == "-2" || arg == "-256") {
flags |= FLAG_MODE_256;
} else if (arg == "--help" || arg == "-help") {
printUsage();
} else if (arg == "-x") {
flags |= FLAG_TELETEXT;
} else if (arg[0] == '-') {
std::cerr << "Error: Unrecognized argument: " << arg << std::endl;
ret = EXITCODE_COMMAND_LINE_USAGE_ERROR;
} else {
// Arguments that will be displayed
if (std::filesystem::is_directory(arg)) {
for (auto &p : std::filesystem::directory_iterator(arg))
if (std::filesystem::is_regular_file(p.path()))
file_names.push_back(p.path().string());
} else {
// Check if file can be opened, @TODO find better way
std::ifstream fin(arg.c_str());
if (fin) {
file_names.push_back(arg);
} else {
std::cerr << "Error: Cannot open '" << arg
<< "', permission issue?" << std::endl;
ret = EXITCODE_NO_INPUT_ERROR;
}
}
}
}
if (detectSize) {
#ifdef _POSIX_VERSION
struct winsize w;
// If redirecting STDOUT to one file ( col or row == 0, or the previous
// ioctl call's failed )
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != 0 ||
(w.ws_col | w.ws_row) == 0) {
std::cerr << "Warning: failed to determine most reasonable size: "
<< strerror(errno) << ", defaulting to 20x6" << std::endl;
} else {
maxWidth = w.ws_col * 4;
maxHeight = w.ws_row * 8;
}
#elif defined _WIN32
CONSOLE_SCREEN_BUFFER_INFO w;
if (GetConsoleScreenBufferInfo(
GetStdHandle(STD_OUTPUT_HANDLE),
&w)) { // just like PowerShell, but without the hyphens, hooray
maxWidth = w.dwSize.X * 4;
maxHeight = w.dwSize.Y * 8;
} else {
std::cerr << "Warning: failed to determine most reasonable size: "
<< std::system_category().message(GetLastError())
<< ", defaulting to 80x24" << std::endl;
}
#else
std::cerr << "Warning: failed to determine most reasonable size: "
"unrecognized system, defaulting to 80x24"
<< std::endl;
#endif
}
if (mode == FULL_SIZE || (mode == AUTO && file_names.size() == 1)) {
for (const auto &filename : file_names) {
try {
cimg_library::CImg<unsigned char> image =
load_rgb_CImg(filename.c_str());
if (image.width() > maxWidth || image.height() > maxHeight) {
// scale image down to fit terminal size
size new_size =
size(image).fitted_within(size(maxWidth, maxHeight));
image.resize(new_size.width, new_size.height, -100, -100,
5);
}
// the actual magic which generates the output
printImage(image, flags);
} catch (cimg_library::CImgIOException &e) {
std::cerr << "Error: '" << filename
<< "' has an unrecognized file format" << std::endl;
ret = EXITCODE_DATA_FORMAT_ERROR;
}
}
} else { // Thumbnail mode
unsigned int index = 0;
int cw = (((maxWidth / 4) - 2 * (columns - 1)) / columns);
int tw = cw * 4;
cimg_library::CImg<unsigned char> image(
tw * columns + 2 * 4 * (columns - 1), tw, 1, 3);
size maxThumbSize(tw, tw);
while (index < file_names.size()) {
image.fill(0);
int count = 0;
std::string sb;
while (index < file_names.size() && count < columns) {
std::string name = file_names[index++];
try {
cimg_library::CImg<unsigned char> original =
load_rgb_CImg(name.c_str());
auto cut = name.find_last_of("/");
sb +=
cut == std::string::npos ? name : name.substr(cut + 1);
size newSize = size(original).fitted_within(maxThumbSize);
original.resize(newSize.width, newSize.height, 1, -100, 5);
image.draw_image(
count * (tw + 8) + (tw - newSize.width) / 2,
(tw - newSize.height) / 2, 0, 0, original);
count++;
unsigned int sl = count * (cw + 2);
sb.resize(sl - 2, ' ');
sb += " ";
} catch (std::exception &e) {
// Probably no image; ignore.
}
}
if (count) printImage(image, flags);
std::cout << sb << std::endl << std::endl;
}
}
return ret;
}

397
src/tiv_lib.cpp Normal file
View file

@ -0,0 +1,397 @@
/*
* Copyright (c) 2017-2023, Stefan Haustein, Aaron Liu
*
* This file is free software: you may copy, redistribute and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* Alternatively, you may copy, redistribute and/or modify this file under
* the terms of the Apache License, version 2.0:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tiv_lib.h"
#include <array>
#include <bitset>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <string>
#include <vector>
const int END_MARKER = 0;
// An interleaved map of 4x8 bit character bitmaps (each hex digit represents a
// row) to the corresponding Unicode character code point.
constexpr unsigned int BITMAPS[] = {
0x00000000, 0x00a0, 0,
// Block graphics
// 0xffff0000, 0x2580, 0, // upper 1/2; redundant with inverse lower 1/2
0x0000000f, 0x2581, 0, // lower 1/8
0x000000ff, 0x2582, 0, // lower 1/4
0x00000fff, 0x2583, 0,
0x0000ffff, 0x2584, 0, // lower 1/2
0x000fffff, 0x2585, 0,
0x00ffffff, 0x2586, 0, // lower 3/4
0x0fffffff, 0x2587, 0,
// 0xffffffff, 0x2588, // full; redundant with inverse space
0xeeeeeeee, 0x258a, 0, // left 3/4
0xcccccccc, 0x258c, 0, // left 1/2
0x88888888, 0x258e, 0, // left 1/4
0x0000cccc, 0x2596, 0, // quadrant lower left
0x00003333, 0x2597, 0, // quadrant lower right
0xcccc0000, 0x2598, 0, // quadrant upper left
// 0xccccffff, 0x2599, // 3/4 redundant with inverse 1/4
0xcccc3333, 0x259a, 0, // diagonal 1/2
// 0xffffcccc, 0x259b, // 3/4 redundant
// 0xffff3333, 0x259c, // 3/4 redundant
0x33330000, 0x259d, 0, // quadrant upper right
// 0x3333cccc, 0x259e, // 3/4 redundant
// 0x3333ffff, 0x259f, // 3/4 redundant
// Line drawing subset: no double lines, no complex light lines
0x000ff000, 0x2501, 0, // Heavy horizontal
0x66666666, 0x2503, 0, // Heavy vertical
0x00077666, 0x250f, 0, // Heavy down and right
0x000ee666, 0x2513, 0, // Heavy down and left
0x66677000, 0x2517, 0, // Heavy up and right
0x666ee000, 0x251b, 0, // Heavy up and left
0x66677666, 0x2523, 0, // Heavy vertical and right
0x666ee666, 0x252b, 0, // Heavy vertical and left
0x000ff666, 0x2533, 0, // Heavy down and horizontal
0x666ff000, 0x253b, 0, // Heavy up and horizontal
0x666ff666, 0x254b, 0, // Heavy cross
0x000cc000, 0x2578, 0, // Bold horizontal left
0x00066000, 0x2579, 0, // Bold horizontal up
0x00033000, 0x257a, 0, // Bold horizontal right
0x00066000, 0x257b, 0, // Bold horizontal down
0x06600660, 0x254f, 0, // Heavy double dash vertical
0x000f0000, 0x2500, 0, // Light horizontal
0x0000f000, 0x2500, 0, //
0x44444444, 0x2502, 0, // Light vertical
0x22222222, 0x2502, 0,
0x000e0000, 0x2574, 0, // light left
0x0000e000, 0x2574, 0, // light left
0x44440000, 0x2575, 0, // light up
0x22220000, 0x2575, 0, // light up
0x00030000, 0x2576, 0, // light right
0x00003000, 0x2576, 0, // light right
0x00004444, 0x2577, 0, // light down
0x00002222, 0x2577, 0, // light down
// Misc technical
0x44444444, 0x23a2, 0, // [ extension
0x22222222, 0x23a5, 0, // ] extension
0x0f000000, 0x23ba, 0, // Horizontal scanline 1
0x00f00000, 0x23bb, 0, // Horizontal scanline 3
0x00000f00, 0x23bc, 0, // Horizontal scanline 7
0x000000f0, 0x23bd, 0, // Horizontal scanline 9
// Geometrical shapes. Tricky because some of them are too wide.
// 0x00ffff00, 0x25fe, 0, // Black medium small square
0x00066000, 0x25aa, 0, // Black small square
// 0x11224488, 0x2571, 0, // diagonals
// 0x88442211, 0x2572, 0,
// 0x99666699, 0x2573, 0,
// 0x000137f0, 0x25e2, 0, // Triangles
// 0x0008cef0, 0x25e3, 0,
// 0x000fec80, 0x25e4, 0,
// 0x000f7310, 0x25e5, 0,
// Teletext / legacy graphics 3x2 block character codes.
// Using a 3-2-3 pattern consistently, perhaps we should create automatic
// variations....
0xccc00000, 0xfb00, FLAG_TELETEXT,
0x33300000, 0xfb01, FLAG_TELETEXT,
0xfff00000, 0xfb02, FLAG_TELETEXT,
0x000cc000, 0xfb03, FLAG_TELETEXT,
0xccccc000, 0xfb04, FLAG_TELETEXT,
0x333cc000, 0xfb05, FLAG_TELETEXT,
0xfffcc000, 0xfb06, FLAG_TELETEXT,
0x00033000, 0xfb07, FLAG_TELETEXT,
0xccc33000, 0xfb08, FLAG_TELETEXT,
0x33333000, 0xfb09, FLAG_TELETEXT,
0xfff33000, 0xfb0a, FLAG_TELETEXT,
0x000ff000, 0xfb0b, FLAG_TELETEXT,
0xcccff000, 0xfb0c, FLAG_TELETEXT,
0x333ff000, 0xfb0d, FLAG_TELETEXT,
0xfffff000, 0xfb0e, FLAG_TELETEXT,
0x00000ccc, 0xfb0f, FLAG_TELETEXT,
0xccc00ccc, 0xfb10, FLAG_TELETEXT,
0x33300ccc, 0xfb11, FLAG_TELETEXT,
0xfff00ccc, 0xfb12, FLAG_TELETEXT,
0x000ccccc, 0xfb13, FLAG_TELETEXT,
0x333ccccc, 0xfb14, FLAG_TELETEXT,
0xfffccccc, 0xfb15, FLAG_TELETEXT,
0x00033ccc, 0xfb16, FLAG_TELETEXT,
0xccc33ccc, 0xfb17, FLAG_TELETEXT,
0x33333ccc, 0xfb18, FLAG_TELETEXT,
0xfff33ccc, 0xfb19, FLAG_TELETEXT,
0x000ffccc, 0xfb1a, FLAG_TELETEXT,
0xcccffccc, 0xfb1b, FLAG_TELETEXT,
0x333ffccc, 0xfb1c, FLAG_TELETEXT,
0xfffffccc, 0xfb1d, FLAG_TELETEXT,
0x00000333, 0xfb1e, FLAG_TELETEXT,
0xccc00333, 0xfb1f, FLAG_TELETEXT,
0x33300333, 0x1b20, FLAG_TELETEXT,
0xfff00333, 0x1b21, FLAG_TELETEXT,
0x000cc333, 0x1b22, FLAG_TELETEXT,
0xccccc333, 0x1b23, FLAG_TELETEXT,
0x333cc333, 0x1b24, FLAG_TELETEXT,
0xfffcc333, 0x1b25, FLAG_TELETEXT,
0x00033333, 0x1b26, FLAG_TELETEXT,
0xccc33333, 0x1b27, FLAG_TELETEXT,
0xfff33333, 0x1b28, FLAG_TELETEXT,
0x000ff333, 0x1b29, FLAG_TELETEXT,
0xcccff333, 0x1b2a, FLAG_TELETEXT,
0x333ff333, 0x1b2b, FLAG_TELETEXT,
0xfffff333, 0x1b2c, FLAG_TELETEXT,
0x00000fff, 0x1b2d, FLAG_TELETEXT,
0xccc00fff, 0x1b2e, FLAG_TELETEXT,
0x33300fff, 0x1b2f, FLAG_TELETEXT,
0xfff00fff, 0x1b30, FLAG_TELETEXT,
0x000ccfff, 0x1b31, FLAG_TELETEXT,
0xcccccfff, 0x1b32, FLAG_TELETEXT,
0x333ccfff, 0x1b33, FLAG_TELETEXT,
0xfffccfff, 0x1b34, FLAG_TELETEXT,
0x00033fff, 0x1b35, FLAG_TELETEXT,
0xccc33fff, 0x1b36, FLAG_TELETEXT,
0x33333fff, 0x1b37, FLAG_TELETEXT,
0xfff33fff, 0x1b38, FLAG_TELETEXT,
0x000fffff, 0x1b39, FLAG_TELETEXT,
0xcccfffff, 0x1b3a, FLAG_TELETEXT,
0x333fffff, 0x1b3b, FLAG_TELETEXT,
0, END_MARKER, 0 // End marker
};
// The channel indices are 0, 1, 2 for R, G, B
unsigned char get_channel(unsigned long rgb, int index) {
return (unsigned char) ((rgb >> ((2 - index) * 8)) & 255);
}
CharData createCharData(GetPixelFunction get_pixel, int x0, int y0,
int codepoint, int pattern) {
CharData result;
result.codePoint = codepoint;
int fg_count = 0;
int bg_count = 0;
unsigned int mask = 0x80000000;
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 4; x++) {
int *avg;
if (pattern & mask) {
avg = result.fgColor.data();
fg_count++;
} else {
avg = result.bgColor.data();
bg_count++;
}
long rgb = get_pixel(x0 + x, y0 + y);
for (int i = 0; i < 3; i++) {
avg[i] += get_channel(rgb, i);
}
mask = mask >> 1;
}
}
// Calculate the average color value for each bucket
for (int i = 0; i < 3; i++) {
if (bg_count != 0) {
result.bgColor[i] /= bg_count;
}
if (fg_count != 0) {
result.fgColor[i] /= fg_count;
}
}
return result;
}
CharData findCharData(GetPixelFunction get_pixel, int x0, int y0,
const int &flags) {
int min[3] = {255, 255, 255};
int max[3] = {0};
std::map<long, int> count_per_color;
// Determine the minimum and maximum value for each color channel
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 4; x++) {
long color = 0;
long rgb = get_pixel(x0 + x, y0 + y);
for (int i = 0; i < 3; i++) {
int d = get_channel(rgb, i);
min[i] = std::min(min[i], d);
max[i] = std::max(max[i], d);
color = (color << 8) | d;
}
count_per_color[color]++;
}
}
std::multimap<int, long> color_per_count;
for (auto i = count_per_color.begin(); i != count_per_color.end(); ++i) {
color_per_count.insert(std::pair<int, long>(i->second, i->first));
}
auto iter = color_per_count.rbegin();
int count2 = iter->first;
long max_count_color_1 = iter->second;
long max_count_color_2 = max_count_color_1;
if ((++iter) != color_per_count.rend()) {
count2 += iter->first;
max_count_color_2 = iter->second;
}
unsigned int bits = 0;
bool direct = count2 > (8 * 4) / 2;
if (direct) {
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 4; x++) {
bits = bits << 1;
int d1 = 0;
int d2 = 0;
unsigned long rgb = get_pixel(x0 + x, y0 + y);
for (int i = 0; i < 3; i++) {
int shift = 16 - 8 * i;
int c1 = (max_count_color_1 >> shift) & 255;
int c2 = (max_count_color_2 >> shift) & 255;
int c = get_channel(rgb, i);
d1 += (c1 - c) * (c1 - c);
d2 += (c2 - c) * (c2 - c);
}
if (d1 > d2) {
bits |= 1;
}
}
}
} else {
// Determine the color channel with the greatest range.
int splitIndex = 0;
int bestSplit = 0;
for (int i = 0; i < 3; i++) {
if (max[i] - min[i] > bestSplit) {
bestSplit = max[i] - min[i];
splitIndex = i;
}
}
// We just split at the middle of the interval instead of computing the
// median.
int splitValue = min[splitIndex] + bestSplit / 2;
// Compute a bitmap using the given split and sum the color values for
// both buckets.
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 4; x++) {
bits = bits << 1;
if (get_channel(get_pixel(x0 + x, y0 + y), splitIndex) > splitValue) {
bits |= 1;
}
}
}
}
// Find the best bitmap match by counting the bits that don't match,
// including the inverted bitmaps.
int best_diff = 8;
unsigned int best_pattern = 0x0000ffff;
int codepoint = 0x2584;
bool inverted = false;
for (int i = 0; BITMAPS[i + 1] != END_MARKER; i += 3) {
if ((BITMAPS[i + 2] & flags) != BITMAPS[i + 2]) {
continue;
}
unsigned int pattern = BITMAPS[i];
for (int j = 0; j < 2; j++) {
int diff = (std::bitset<32>(pattern ^ bits)).count();
if (diff < best_diff) {
best_pattern = BITMAPS[i]; // pattern might be inverted.
codepoint = BITMAPS[i + 1];
best_diff = diff;
inverted = best_pattern != pattern;
}
pattern = ~pattern;
}
}
if (direct) {
CharData result;
if (inverted) {
long tmp = max_count_color_1;
max_count_color_1 = max_count_color_2;
max_count_color_2 = tmp;
}
for (int i = 0; i < 3; i++) {
int shift = 16 - 8 * i;
result.fgColor[i] = (max_count_color_2 >> shift) & 255;
result.bgColor[i] = (max_count_color_1 >> shift) & 255;
result.codePoint = codepoint;
}
return result;
}
return createCharData(get_pixel, x0, y0, codepoint, best_pattern);
}
int clamp_byte(int value) {
return value < 0 ? 0 : (value > 255 ? 255 : value);
}
double sqr(double n) { return n * n; }
int best_index(int value, const int STEPS[], int count) {
int best_diff = std::abs(STEPS[0] - value);
int result = 0;
for (int i = 1; i < count; i++) {
int diff = std::abs(STEPS[i] - value);
if (diff < best_diff) {
result = i;
best_diff = diff;
}
}
return result;
}

99
src/tiv_lib.h Normal file
View file

@ -0,0 +1,99 @@
/*
* Copyright (c) 2017-2023, Stefan Haustein, Aaron Liu
*
* This file is free software: you may copy, redistribute and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* Alternatively, you may copy, redistribute and/or modify this file under
* the terms of the Apache License, version 2.0:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TIV_LIB_H
#define TIV_LIB_H
#include <array>
#include <functional>
// Implementation of flag representation for flags in the main() method
constexpr int FLAG_FG = 1;
constexpr int FLAG_BG = 2;
constexpr int FLAG_MODE_256 = 4; // Limit colors to 256-color mode
constexpr int FLAG_24BIT = 8; // 24-bit color mode
constexpr int FLAG_NOOPT = 16; // Only use the same half-block character
constexpr int FLAG_TELETEXT = 32; // Use teletext characters
// Color saturation value steps from 0 to 255
constexpr int COLOR_STEP_COUNT = 6;
constexpr int COLOR_STEPS[COLOR_STEP_COUNT] = {0, 0x5f, 0x87, 0xaf, 0xd7, 0xff};
// Grayscale saturation value steps from 0 to 255
constexpr int GRAYSCALE_STEP_COUNT = 24;
constexpr int GRAYSCALE_STEPS[GRAYSCALE_STEP_COUNT] = {
0x08, 0x12, 0x1c, 0x26, 0x30, 0x3a, 0x44, 0x4e, 0x58, 0x62, 0x6c, 0x76,
0x80, 0x8a, 0x94, 0x9e, 0xa8, 0xb2, 0xbc, 0xc6, 0xd0, 0xda, 0xe4, 0xee};
typedef std::function<unsigned long(int, int)> GetPixelFunction;
int clamp_byte(int value);
int best_index(int value, const int STEPS[], int count);
double sqr(double n);
/**
* @brief Struct to represent a character to be drawn.
* @param fgColor RGB
* @param bgColor RGB
* @param codePoint The code point of the character to be drawn.
*/
struct CharData {
std::array<int, 3> fgColor = std::array<int, 3>{0, 0, 0};
std::array<int, 3> bgColor = std::array<int, 3>{0, 0, 0};
int codePoint;
};
// Return a CharData struct with the given code point and corresponding averag
// fg and bg colors.
CharData createCharData(GetPixelFunction get_pixel, int x0, int y0,
int codepoint, int pattern);
/**
* @brief Find the best character and colors
* for a 4x8 part of the image at the given position
*
* @param image
* @param x0
* @param y0
* @param flags
* @return CharData
*/
CharData findCharData(GetPixelFunction get_pixel, int x0, int y0,
const int &flags);
#endif

View file

@ -1,40 +1,26 @@
class Terminalimageviewer < Formula
desc "Display images in a terminal using block graphic characters"
homepage "https://github.com/stefanhaustein/TerminalImageViewer"
url "https://github.com/stefanhaustein/TerminalImageViewer/archive/v1.1.0.tar.gz"
sha256 "727ddaa048643cb0a13e23bc308415060d99d8b1853883ad339ad7b952050d61"
head "https://github.com/stefanhaustein/TerminalImageViewer.git"
uses_from_macos "curl" => :test
depends_on "gcc" => :build unless OS.linux?
url "https://github.com/stefanhaustein/TerminalImageViewer/archive/refs/tags/v1.1.1.tar.gz"
sha256 "9a5f5c8688ef8db0e88dfcea6a1ae30da32268a7ab7972ff0de71955a75af0db"
license "Apache-2.0"
head "https://github.com/stefanhaustein/TerminalImageViewer.git", branch: "master"
depends_on "imagemagick"
def install
cd "src/main/cpp" do
system "make"
if OS.mac?
# No expermimental/filesystem.h on mac.
system "/usr/local/bin/g++-#{Formula["gcc"].version_suffix}", "-std=c++17",
"-Wall",
"-fpermissive",
"-fexceptions",
"-O2", "-c",
"-L/usr/local/opt/gcc/lib/gcc/11/",
"tiv.cpp", "-o", "tiv.o"
system "/usr/local/bin/g++-#{Formula["gcc"].version_suffix}", "tiv.o", "-o", "tiv",
"-L/usr/local/opt/gcc/lib/gcc/11/", "-pthread", "-s"
else
system "make"
end
system "/usr/local/bin/g++-#{Formula["gcc"].version_suffix}", "-std=c++17", "-Wall", "-fpermissive",
"-fexceptions", "-O2", "-c", "-L/usr/local/opt/gcc/lib/gcc/#{Formula["gcc"].version_suffix}/", "tiv.cpp",
"-o", "tiv.o"
system "/usr/local/bin/g++-#{Formula["gcc"].version_suffix}", "tiv.o", "-o", "tiv",
"-L/usr/local/opt/gcc/lib/gcc/#{Formula["gcc"].version_suffix}/", "-pthread", "-s"
bin.install "tiv"
end
end
test do
# Downloads a public domain test file from wikimedia commons and displays it.
# NOTE: Test will fail. Will fix when I get to my mac.
system "curl -o \"test.png\" https://upload.wikimedia.org/wikipedia/commons/2/24/Cornell_box.png"
assert_equal "▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
",
shell_output("#{bin}/tiv -0 -w 400 -h 400 test.png").strip
assert_equal "\e[48;2;0;0;255m\e[38;2;0;0;255m \e[0m",
shell_output("#{bin}/tiv #{test_fixtures("test.png")}").strip
end
end

32
tiv.rb
View file

@ -1,32 +0,0 @@
class Tiv < Formula
desc "Display images in a terminal using block graphic characters"
homepage "https://github.com/stefanhaustein/TerminalImageViewer"
url "https://github.com/stefanhaustein/TerminalImageViewer/archive/v1.1.0.tar.gz"
sha256 "727ddaa048643cb0a13e23bc308415060d99d8b1853883ad339ad7b952050d61"
head "https://github.com/stefanhaustein/TerminalImageViewer.git"
uses_from_macos "curl" => :test
depends_on "imagemagick"
def install
cd "src/main/cpp" do
if OS.mac?
system "c++", "-std=c++17", "-Wall", "-fpermissive", "-fexceptions", "-O2",
"-c", "tiv.cpp", "-o", "tiv.o"
system "c++", "tiv.o", "-o", "tiv", "-L/usr/local/opt/gcc/lib/gcc/11/", "-pthread",
"-s"
else
system "make"
end
bin.install "tiv"
end
end
test do
# Downloads a public domain test file from wikimedia commons and displays it.
# NOTE: Test will fail. Will fix when I get to my mac.
system "curl -o \"test.png\" https://upload.wikimedia.org/wikipedia/commons/2/24/Cornell_box.png"
assert_equal "▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
",
shell_output("#{bin}/tiv -0 -w 400 -h 400 test.png").strip
end
end