Command Line – Resizing Images GIMPless

Fairly often I’ll find a desktop that I like on the Internet and download it. Usually the process is that it’s not the correct size for my desktop and I’ll open up Gimp and resize it. This can be a bit of a time taker if there is only one image. Imagemagick can do the job from the command line possibly faster.

For example, last night, I snatched a wallpaper from IamFreeman. Its a good wallpaper with rough texture, nice and simple. Now to resize it to the desktop size I use imagemagick’s mogrify or convert program. Mogrify tranforms the image meaning making mistakes = bad, convert will write a new image. I use mogrify here, if using convert specify the new filename at the end of the line.

If I just wanted the top left part of the image, I could just crop it.

mogrify Clean_is_simple_by_iAmFreeman.jpg -crop 800x600+0+0

The 0+0 specifies the top-left portion of the image. But I don’t want to just crop the top left, I want the whole image scaled down.

Since the proportions aren’t equal between my screens aspect ratio 4:3 (800×600) and the desktop I choose is 5:4 (1280×1024), I’d need to crop part of the image before I resize. The image dimensions can be listed with the identify command:

identify Clean_is_simple_by_iAmFreeman.jpg 
Clean_is_simple_by_iAmFreeman.jpg JPEG 1280x1024 1280x1024+0+0 DirectClass 8-bit 729.758kb 0.700u 0:02

To discover if height or width needs to be cropped, find the difference of the aspects:

echo "scale=5;(1280/1024)/(800/600)" | bc
.93750

This tells me proportionally the 5:4 picture is taller. If the value is less that one then the height needs to be cropped, greater than one and the width needs to be cropped. In this instance, the height needs to be cropped 93.75%. If the width needs to be cropped:

echo "scale=5;(1280/800)/(800/600)" | bc
1.20000
echo "scale=5;(100/1.2)" | bc
83.33333

To use mogrify to crop, tell the x and y in percentages:

mogrify Clean_is_simple_by_iAmFreeman.jpg -crop 100%x93.75%+0+0

Purists will say that, this isn’t’ good. That god will walk upon the earth and smite thee. Yes, and he’d be right to. Here:

mogrify Clean_is_simple_by_iAmFreeman.jpg -crop 100%x93.75%+0+32

I specified in the previous command 0+0 (the crop value from the top left) hence the bottom portion was cut off in the previous command. Since the image is being reduced to 960 pixels height and since – (1024 – 960)/2 will give us the proper offset. The image is now centered. (+) values will crop x and y from the top left, (-) values will crop x and y from the bottom right.

    +        -
    ___________
+  |           |
   |           |
   |           |
-  |___________|

OMG, what a pain!

Anyways, its easy to resize now:

mogrify -resize 800 Clean_is_simple_by_iAmFreeman.jpg

I only specified the width here as specifying height would be redundant. If the image needs to be stretched or compressed use an ! after the value (800×500!).

All in One Command

Put the steps in order and this can be done in one command.

mogrify Clean_is_simple_by_iAmFreeman.jpg -crop 100%x93.75%+0+32 -resize 800

Resources

I’ll talk about converting SVGs tomorrow and how I take screenshots.

Publishing a Blog in Vim with Vimpress

Publishing a Blog in Vim with VimpressI like blogging. :)

I learned though that writing blogs is an art in organization and learning the tools used to make them. I reviewed blogging software before and said that I really liked Drivel. This week though may have changed all that. I decided to crash test Vimpress and test how she does. Now, I can say I’m really impressed. I am very possibly going to keep using it.

Vimpress is a plugin for Vim that allows editing and added posts to WordPress blogs. Vimpress also will list the posts written to easily go back and edit them. Blogging is as simple as BlogList, BlogNew, BlogOpen and BlogSend. Installation is easy enough, just put the blog and syntax file in their respective folders:

tar zxvf vimpress.tar.gz -C ~/.vim

Edit ~/.vim/plugin/blog.vim to point to WordPress php-file. Mine for example is https://linuxtidbits.wordpress.com/xmlrpc.php. And Vimpress will be ready. For more look at Vimpress’s homepage.

After I set it up, Typing in Vim and publishing in Vimpress does so without a hitch. Very nice. A couple things to keep in mind to help ease the transition…

Html markup will have to be learned. Only the basic tags need to be learned though (a href, img, pre…) not too bad. Also I find that the closetag plugin is a good idea. The closetag plugin maps ctrl-_ to close the tag. A few lines will need to be added to the ~/.vimrc for it to be active:

" Automatic tag closing for html and xml (closetag plugin)
autocmd Filetype html,xhtml,xml,xsl source ~/.vim/scripts/closetag.vim
let g:closetag_html_style=1
source ~/.vim/scripts/closetag.vim

Vimpress comes with a syntax file that highlights the BlogList and header, if html syntaxing is desired its easy enough to set:

:setfiletype html

I was hoping to find a way to nest html in the syntax file but haven’t just yet found out how.

Publishing a Blog in Vim with Vimpress

Anyways, I’ve really liking using Vim and Vimpress so far. As I’ve said previously the learning scale is a bit more but well worth it. I need to learn some more about cutting and pasting in Vim (to and from the Xserver) to really be effective but I’m getting there.

Vim Setup – Tuning Vim To The Environment

Vim is best used when it is configured for the users needs. Vim has a slew of configurations to develop the type of environment the user requires to do numerous different tasks from spell checking to color syntaxing. There are thousands of scripts and color themes available on the Vim website that can add even more abilities.

I talked yesterday of learning Vim and perhaps just as important is tailoring one’s own configuration file (~/.vimrc). The best place to start is finding a person’s ~/.vimrc who is already experienced in Vim. Some distro’s may install a custom ~/.vimrc already so it’s best to take a look. I personally use Brians Carpers ~/.vimrc which does a good job for me. There are literally thousands out there and people like to share them, so pick the right one for whatever Vim needs to do.

Aesthetics

Setting up the terminal and Vim correctly are important parts for long periods in front of the terminal. To help ease reading and prevent eye strain a couple things that can help are choosing a lower-contrast colorscheme and properly sizing the width of the terminal

Colorscheme:

To pick a colorscheme that is comfortable for viewing for long periods go ahead and start up Vim – /etc/X11/xorg.conf can provide a good example. Now type:

colorscheme 

follow by a space. Now press “tab” for tab-completion – pressing tab will cycle through the available color schemes. For example, this one is called pyte:

72 Section "InputDevice"
73     Identifier "Generic Keyboard"
74     Driver     "kbd"
75     Option     "CoreKeyboard"
76 #   Option      "XkbRules"      "pc104"    
77     Option     "XkbLayout"        "us"
78     Option      "XkbLayout"     "en_US"
79     Option     "XkbModel"     "macintosh" 
80 #   Option      "XkbVariant"    "apple"
81 EndSection
82
83 Section "InputDevice"
84     Identifier "Configured Mouse"
85     Driver     "mouse"
86     Option     "CorePointer"
87     Option     "Device"       "/dev/input/mice"
88     Option     "Protocol"     "auto"
89     Option     "ZAxisMapping" "4 5"
90 EndSection

For xterm users (gnome-terminal, stjerm, tilda?, others?…) it’s likely that the terminal is set to eight bit color for compatibility reasons (see my post from a couple days ago). Vim though can display in 256 colors and will need to for alot of these colorschemes to work. To set Vim to 256 colors, add the setting to the ~/.vimrc

set t_Co_256

New colorschemes can be found in at the Vim website. To get a good idea what they look like before installed take a look at Vim Color Scheme Test. Color schemes need to be put in ~/.vim/colors and then a color scheme can be permanently added by putting them in the ~/.vimrc:

colorscheme blue

Terminal Width

The width of the terminal is also important. The human eye can only scan about 10 words before it loses focus (i.e. has difficulty scanning to the next line). Most text in Linux is written with a margin of 72 or 80 characters. Most editors also use a soft-returns (i.e. not a hard line break). Use whatever is best by resizing the window to fit this many characters. Vim cannot set a soft-return and rather uses the window width. This is unfortunate as some terminal apps (tilda, and yakuake) use the entire width of the screen – yes vim has settings like “textwidth” and “wrapmargin” but they create hard-returns, so having a wide terminal is not a good idea with Vim.

V Tips

A few tips I picked up along the line.

  • Vim has great help documentation. :help topic can be done on about anything.
  • Vim has tab-completion for entering commands and bash-completion for files (e.g. :w ~/Desktop/myblog.txt)
  • The mouse can be used in Vim for some functions, but it needs to be enabled. I use this setting as I find that moused in visual mode can be distractive.
  • set mouse=ni
  • To be able to select text with the mouse in this mode hold the shift key
  • I       Insert at beginning of line
    A       Append to end of line

  • Tab-mode rules:
    vim -p doc1 doc2
    gt      go through tabs
    :tabnew To open new tab

  • Append a file:
    :w >> ~/My-lousy-document
  • Check spelllinng:
    :setlocal spell spelllang=en_us
    :setlocal nospell
    ]s      next word
    [s      previous word
    z=      word suggestions
  • Spelling can be mapped to a key if used frequently enough, in my ~/.vimrc I mapped spelling the the F7 key:
    map <F7> <Esc>:setlocal spell spelllang=en_us
    map <S-F7> <Esc>:setlocal nospell
  • I like to alway have tabs so I put these in my ~/.bashrc to have tabs every time I open a file:
  • alias v="vim -p"
    alias sv="sudo vim -p"

My Terminal – Gush

Vim Setup - Tuning Vim To The Environment 

Command line to xclipboard

Update: Script has been updated to add pipe support. Thanks to Nathan who allowed me to use his improvements.

It’s really something to be learning Linux. The more I learn about Linux the more I learn it’s about manipulating letters and numbers (well, this is more programming than anything but Linux is a lot about that). Bash I’m discovering is great; I’m just getting into it and now have made things a good deal easier by learning how to copy and paste text from the command line via the Xorg server clipboard. Here is a couple commands that can do it with examples, following them are a couple bash scripts that make this easy as can beasy.

The Programs

xsel and xclip are command line programs that can redirect the contents of the Xorg server clipboard. The Xorg server has two clipboards: the common right-click > Copy, and one for the middle-mouse click. For those that don’t know of it yet, the middle-click clipboard allows quick copy and pasting without having to enter a menu or using Ctrl + v. Anytime you select text on the Xorg server there is a separate register that records this text, then clicking the middle-mouse button (sometimes called the mouse button three [usually done by clicking down the scroll wheel] will paste the text. The Xorg server defines the the middle-click clipboard as primary and the right-click clipboard as secondary.

xclip

Here are the basics of using xclip. xclip, I prefer over xsel because I have found that xsel can have problems pasting to java apps.

xclip can be used in a variety of ways. First, for example, it can be piped to:

echo "hi" | xclip -selection clipboard

This will copy to the standard clipboard. For abbreviation, you can use c instead of clipboard. You can specify primary or p here too to copy to the middle-mouse button, but isn’t necessary as this is the default for xclip.

echo "hello" | xclip

To direct a file to xclip the -in or -out options are needed:

xclip -in -selection c <filename>
xclip -out -selection c <filename>

Which will respectively put a file into the clipboard, and write to a file from the clipboard contents.

To make the process quicker, I’ve created a couple scripts to automate the tasks called cb-in and cb-out and can be used like a standard command:

cb-in pack 
 File pack copied to the clipboard

cb-in

cb-out

xsel

To copy to the context-menu clipboard:

xsel --clipboard < /etc/fstab

To copy a text to the middle mouse button clipboard:

xsel < /etc/fstab

xsel can be piped too:

echo "a-bit-of-text" | xsel -b
cat /etc/make.conf | xsel -b

To output directly to the terminal:

xsel --clipboard

And to redirect and append to a file:

xsel --clipboard > Baada-Boom.txt
xsel --clipboard >> ~/.Baada-Boom

cp2clip (xsel)

#!/bin/bash
# cp2clip - copy to the clipboard the contents of a file

# Program name from it's filename
prog=${0##*/}

# Text color variables
bldblu='\e[1;34m'         # blue
bldred='\e[1;31m'         # red
bldwht='\e[1;37m'         # white
txtbld=$(tput bold)       # bold
txtund=$(tput sgr 0 1)    # underline
txtrst='\e[0m'            # text reset
info=${bldwht}*${txtrst}
pass=${bldblu}*${txtrst}
warn=${bldred}!${txtrst}

filename=$@

# Display usage if full argument isn't given
if [[ -z $filename ]]; then
    echo " $prog <filename> - copy a file to the clipboard"
    exit
fi

# Check that file exists
if [[ ! -f $filename ]]; then
  echo -e "$warn File ${txtund}$filename${txtrst} doesn't exist"
  exit
fi

# Check user is not root (root doesn't have access to user Xorg server)
if [[ $(whoami) == root ]]; then
  echo -e "$warn Must be regular user to copy a file to the clipboard"
  exit
fi

# Copy file to clipboard, give feedback
xsel --clipboard < "$filename"
echo -e "$pass ${txtund}"${filename##*/}"${txtrst} copied to clipboard"

clippaste (xsel)

#!/bin/bash
# clippaste - Paste contents of clipboard to file in terminal.
# use 'xclip -out -selection primary' for middle click clipboard

# Program name from it's filename
prog=${0##*/}

# Text color variables
bldblu='\e[1;34m'         # blue
bldred='\e[1;31m'         # red
bldwht='\e[1;37m'         # white
txtbld=$(tput bold)       # bold
txtund=$(tput sgr 0 1)    # underline
txtrst='\e[0m'            # text reset
info=${bldwht}*${txtrst}
pass=${bldblu}*${txtrst}
warn=${bldred}!${txtrst}

filename=$@
pasteinfo="clipboard contents"

# usage if argument isn't given
if [[ -z $filename ]]; then
  echo "clippaste <filename> - paste contents of context-menu clipboard to file"
  exit
fi

# check if file exists, prompt to append or override, else create new
if [[ -f $filename ]]; then
  echo -en "$warn File ${txtund}$filename${txtrst} already exists - (${txtbld}e${txtrst})xit, (${txtbld}a${txtrst})ppend, (${txtbld}o${txtrst})verwrite: "
  read edit
  case "$edit" in
    [aA] )  xsel --clipboard >> $filename
            echo -e "$pass File ${txtund}$filename${txtrst} appended with clipboard contents"
            ;;
    [oO] )  xsel --clipboard > $filename
            echo -e "$pass File ${txtund}$filename${txtrst} overwrote with clipboard contents"
            ;;
    * )     exit
    esac; else
    xsel --clipboard >> $filename
    echo -e "$pass File ${txtund}"$filename"${txtrst} created with clipboard contents"
fi

Purge memory trick

Purge Memory

Linux does a good job when it comes to memory allocation. If memory isn’t being used or hasn’t been used for awhile it gets put into a cache where it can readily pulled. At times though this cache can become pretty big (especially for a program that has a memory leak). If a good number of programs are being used or if memory is limited then Linux will begin using hard disk swap which can really bog down performance. In these instances, it may help to purge the memory.

In the terminal type free -m to see memory usage. Flushing the filesystem buffers and to drop extra caches can be done by doing:

sudo sync
sudo echo 3 | sudo tee /proc/sys/vm/drop_caches

Look once more at free -m and memory usage should be improved. Freeing memory is most effective by shutting down whatever programs can be. To be really effective shutdown X server first.

This can be put in a script if you need to regularly do this:

Low processor gaming

Having a computer several years old doesn’t stop you from being able to play a good game on Linux. In fact, having an older computer is perfect with Linux – there are tons and tons of games! These games I’m running are on an iBook 300MHz processor and they all perform worthy.

Every several weeks I like to try a new game, lately I’ve got a chance to try three and I can say these are all excellent games.

Kobo Deluxe

Kobo Deluxe is a top down 2D shooter where we have to dodge enemy ships, evade bullets, and destroy space platforms. Kobo is a basic game but when dozens of bullets are flying your way and enemy pilots buzzing around you it is quite a challenge. Kobo Deluxe has 50 levels, only of which 24 have I got through after a good amount of play. There is quite a bit of braggart around for those who are able to finish it.

Light Burden Gaming

Ivan – Iter Vehemens ad Necem

“Iter Vehemens ad Necem” is latin for Violent Road to Death. Eck! Yes, my latin was a bit rusty too. Ivan looks to be one of the cooler games to play, I’ve only just installed it but it reminds me of my Ultima IV trudge through dungeons marathons. IVAN is a roguelike game with a graphical interface. No attack gremlin with level 14+ electrical mace :) here so it doen’st have a large learning scale. IVAN can be dived into without needing to read a manual. The objective of IVAN is to get the character to travel to a far off island by means of an underground dungeon to deliver a very important message (oh, and there happens to be a few monsters along the way.) IVAN is unique in rogue-likes and includes a detailed body part system and physical property system. Be careful not to die in IVAN as no magical potion will save you. Death = polly parrot. Ivan is a fun game and though I just started I think I’ll be playing it quite a bit. Unfortunately, I’m bogged by the bug that creates a Segmentation Fault on some PCs. Is it possible to play IVAN all the way thorough without saving?

Ivan pic

FYI, several fans have created a new forum for IVAN and a nice wiki that can be helpful.

OpenTyrian

Loitering the Linux Game Tome a few days ago, I gold mined OpenTyrian – right away my eyebrows raised. Tyrian was a blast DOS game on one of my earlier PC’s. Tyrian is a fast paced scrolling shooter that includes upgrades and challenging bosses. The port of the original Tyrian uses C and SDL and is nice and responsive though sound at time crackles on me.

OpenTyrian

Not many repositories have this game yet so it will need to be compiled from source. The original data files (also at the site) will need to be put in a “data” folder where the executable is.

I created a .desktop for OpenTyrian to show under the Gnome menu, but unfortunately the desktop launcher must look at the files relatively and thus can’t find the data files this way. The only way I could find a way around it was to create a script that cd‘d to the opentyrian folder and executed tyrian from there.

vim /usr/bin/opentyrian

#!/bin/bash
cd /home/user/opentyrian
./tyrian

To create the .desktop file:

vim ~/.local/share/applications/opentyrian.desktop

[Desktop Entry]
Name=OpenTyrian
Type=Application
Comment=OpenTyrian is a port of the classic DOS game Tyrian to C using SDL
Exec=opentyrian
TryExec=opentyrian
Icon=opentyrian
Categories=Game;ArcadeGame;

Here’s a few icons I extracted from the game for the .desktop file:

24×24
ot-24

32×32
ot-32

Original
origianl-ty

Usually it’s easiest to put them in the pixmaps directory:
sudo cp ~/Desktop/opentyrian-*.png /usr/share/pixmaps/opentyrian.png

In a few weeks, I’ll review my favorite Linux game: Wesnoth.

Old School Gaming and a Gnome Thought

— Old School Gaming and a Gnome Thought — The iBook is not a powerhouse of computing so I’ve been trying some old school games ( A transition I’m beginning to like ). Last Sunday I discussed a couple such games, Cave Story and Nazghul/Haxima, this week I’ve tried several more.

Bible Dave

Bible Dave is a pious Pitfall game. Dave must locate the lost bibles after a plane crash. Playing this reminded me of how much I like the old pitfall game ( I still wonder if it ever had an ending ). Three of the games I tried used SDL. I wasn’t sure if using SDL would create a performance issue, but for the most part no. Bible Dave was the expection. A 300 MHz processor and a 4MB video card isn’t enough for this game. Processors above this should be able to handle Bible Dave fine. Tecnoballz in not part of Gentoo’s portage and will need to be compiled on it’s own.

bible dave screen

Technoballz

Technoballz is another SDL game, a modern breakout clone. Tecnoballz runs pretty smoothly and is alot of fun to play. It features tons and tons of powerups, and the ability to buy powerups as the game progresses. Tecnoballz also in not part of portage and will need to be compiled.

tecnoballz screen

A couple bits seemed missing during compiling that I had to fix in order for it to run. From the source directory:


mkdir ~/.tlkgames
cp tecnoballz.conf ~/.tlkgames/
cd src/TecnoballZ/
sudo cp levels-data.xml /usr/local/share/tecnoballz/
sudo cp -r texts /usr/local/share/tecnoballz/

I also created a .desktop entry for it.

[Desktop Entry]
Version=1.0
Name=TecnoballZ
Type=Application
Comment=An SDL Breakout clone.
Exec=/usr/local/games/tecnoballz
TryExec=/usr/local/games/tecnoballz
Icon=tecnoballz.png
Categories=Game;ArcadeGame;

tkgames

tkgames is a collection of nice basic puzzle games – solitaire, spider, hangman, and a few others. Not really the action games like above but fun none-the-less. I particularly like poly puzzle.

tksolitaire screen

tkgames is not in portage and requires tk and tcl to run.

My thought for an addition to Gnome, what do you think?

How about apps the are minimized become iconized:

minimized thoughts

Hmm?