Displaying A List Of All Available Fonts Using Java

Most of the tutorials I write in my blogs are because one way or the other I need these programs for myself. I recently ran into a similar situation. I was working on one of application where I was trying to resize an image and put a water mark on top of this image. (This will be my upcoming tutorial). Then I needed a good looking font. I knew there are lots of Fonts installed on my machine, and I can get a preview of them when I use Adobe Photoshop. But I had no idea what would their names be to be used in my application. So I did a little research and wrote this program that list all available fonts from the local system.

First I found the method from ToolKit class. I wrote a simple class to use that method. To my wonder, it just printed 5 fonts. Definitely I didn’t have just five fonts in my machine. The method I used Toolkit.getDefaultToolkit().getFontList(), which I later discovered was a depricated method and only provided me a few primitive fonts.

So, another small research led me to GraphicsEnvironment.getAvailableFontFamilyNames() method which was what I exactly wanted. It listed the names of all the fonts that are available in my machine.

I am presenting you here a class that uses both the methods mentioned above to find a list of available fonts.

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On: 05-21-2009
 */
package com.kushal.utils;

import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;

/**
 * Demonstrating  How To Get the
 * Available Font Names Using Java
 *
 */
public class AvailableFontLister {

	public static void main(String args [])
	{
		System.out.println("***************************");
		System.out.println("**Listing Fonts Using Deprecated Method From ToolKit Class**");
		listUsingToolKit();
		System.out.println();

		System.out.println("****************************");
		System.out.println("**Listing Fonts Using Method From GraphicsEnvironment Class**");
		listUsingGraphicsEnvironment ();

	}

	/**
	 * Prints a list of all available fonts from
	 * the local graphics environment.
	 *
	 * The output list varies from manchine to machine
	 */
	public static void listUsingGraphicsEnvironment ()
	{
		GraphicsEnvironment ge= null;

		ge=GraphicsEnvironment.getLocalGraphicsEnvironment();

		String []fontNames=ge.getAvailableFontFamilyNames();

		for (int i = 0; i< fontnames.length; i++) {
			System.out.println(fontnames[i]);
		}
	}

}

———————————–
Sample Output Of This Program On My Machine

***************************
**Listing Fonts Using Deprecated Method From ToolKit Class**
Dialog
SansSerif
Serif
Monospaced
DialogInput
<!--more-->
****************************
**Listing Fonts Using Method From GraphicsEnvironment Class**
Agency FB
Algerian
Arial
Arial Black
Arial Narrow
Arial Rounded MT Bold
Arial Unicode MS
Baskerville Old Face
Bauhaus 93
Bell MT
Berlin Sans FB
Berlin Sans FB Demi
Bernard MT Condensed
Blackadder ITC
Bodoni MT
Bodoni MT Black
Bodoni MT Condensed
Bodoni MT Poster Compressed
Book Antiqua
Bookman Old Style
Bookshelf Symbol 7
Bradley Hand ITC
Britannic Bold
Broadway
Brush Script MT
Calibri
Californian FB
Calisto MT
Cambria
Cambria Math
Candara
Castellar
Centaur
Century
Century Gothic
Century Schoolbook
Chiller
Colonna MT
Comic Sans MS
Consolas
Constantia
Cooper Black
Copperplate Gothic Bold
Copperplate Gothic Light
Corbel
Courier New
CourierThai
Curlz MT
Devanagari MT for IBM
Dialog
DialogInput
Edwardian Script ITC
Elephant
Engravers MT
Eras Bold ITC
Eras Demi ITC
Eras Light ITC
Eras Medium ITC
Estrangelo Edessa
Felix Titling
Footlight MT Light
Forte
Franklin Gothic Book
Franklin Gothic Demi
Franklin Gothic Demi Cond
Franklin Gothic Heavy
Franklin Gothic Medium
Franklin Gothic Medium Cond
Freestyle Script
French Script MT
Garamond
Gautami
Georgia
Gigi
Gill Sans MT
Gill Sans MT Condensed
Gill Sans MT Ext Condensed Bold
Gill Sans Ultra Bold
Gill Sans Ultra Bold Condensed
Gloucester MT Extra Condensed
Goudy Old Style
Goudy Stout
Haettenschweiler
Harlow Solid Italic
Harrington
High Tower Text
Impact
Imprint MT Shadow
Informal Roman
Jokerman
Juice ITC
Kristen ITC
Kunstler Script
Latha
Lucida Bright
Lucida Calligraphy
Lucida Console
Lucida Fax
Lucida Handwriting
Lucida Sans
Lucida Sans Typewriter
Lucida Sans Unicode
Magneto
Maiandra GD
Mangal
Marlett
Matura MT Script Capitals
Microsoft Sans Serif
Mistral
Modern No. 20
Monospaced
Monotype Corsiva
MS Mincho
MS Outlook
MS Reference Sans Serif
MS Reference Specialty
MT Extra
MV Boli
Niagara Engraved
Niagara Solid
OCR A Extended
Old English Text MT
Onyx
Palace Script MT
Palatino Linotype
Papyrus
Parchment
Perpetua
Perpetua Titling MT
Playbill
Poor Richard
Pristina
Raavi
Rage Italic
Ravie
Rockwell
Rockwell Condensed
Rockwell Extra Bold
SansSerif
Script MT Bold
Segoe UI
Serif
Showcard Gothic
Shruti
Snap ITC
Stencil
Sylfaen
Symbol
Tahoma
Tempus Sans ITC
Thonburi
Times New Roman
Trebuchet MS
Tunga
Tw Cen MT
Tw Cen MT Condensed
Tw Cen MT Condensed Extra Bold
Verdana
Viner Hand ITC
Vivaldi
Vladimir Script
Webdings
Wide Latin
Wingdings
Wingdings 2
Wingdings 3

P.S. This article was previously published in my another blog at Sanjaal.com

Cropping An Image In Java [Sample/Tutorial With Source Code]

Cropping refers to the removal of the outer parts of an image to improve framing, accentuate subject matter or change aspect ratio. Depending on the application, this may be performed on a physical photograph, artwork or film footage, or achieved digitally using image editing software. The term is common to the film, broadcasting, photographic, graphic design and printing industries.

In the printing, graphic design and photography industries, cropping refers to removing unwanted areas from a photographic or illustrated image. One of the most basic photo manipulation processes, it is performed in order to remove an unwanted subject or irrelevant detail from a photo, change its aspect ratio, or to improve the overall composition. In telephoto photography, most commonly in bird photography, an image is cropped to magnify the primary subject and further reduce the angle of view when a lens of sufficient focal length to achieve the desired magnification directly is not available. It is considered one of the few editing actions permissible in modern photojournalism along with tonal balance, colour correction and sharpening. A crop made from the top and bottom of a photograph may produce an aspect which mimics the panoramic format (in photography) and the widescreen format in cinematography and broadcasting. Both of these formats are not cropped as such, rather the product of highly specialised optical configuration and camera design. [Wikipedia]

The following picture shows the cropping are lying within the image.

The following image shows portions of cropping area lying outside the original image

The following program written in java show how image cropping can be done easily. The program takes an image and the cropping parameters as input.
Then it determines if the cropping area lies within the image or not. In case a cropping area in portion or fully lies outside the main image co-ordinates, the program adjusts the crop area.

The parameters used in the cropping are:
— Height of the cropping rectangle.
— Width of the cropping rectangle.
— X Co-ordinate of the start point of the cropping rectangle.
— Y Co-ordinate of the start point of the cropping rectangle.

The program also takes care of the negative co-ordinates supplied for the crop area rectangle.

Finally the program crops the input image and saves a copy of the cropped image.

You can find more comments int the java program itself.

package com.kushal.graphics;
/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 2009-10-08
 *
 * This utility crops an image with the provided
 * crop parameters (crop rectangle dimension and
 * rectangle start co-ordinates)
 */
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.RasterFormatException;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageCropper {

static Rectangle clip;

public static void main(String args[]) throws Exception {
String inputFileLocation = "C:/temp/myImage02.jpg";
String outputFileLocation = "C:/temp/myImage-cropped.jpg";

System.out.println("Reading Original File : " + inputFileLocation);

BufferedImage originalImage = readImage(inputFileLocation);

/**
* Image Cropping Parameters
*/
int cropHeight = 150;
int cropWidth = 150;
int cropStartX = 50;
int cropStartY = 50;

BufferedImage processedImage = cropMyImage(originalImage, cropWidth,
cropHeight, cropStartX, cropStartY);

System.out.println("Writing the cropped image to: "
+ outputFileLocation);
writeImage(processedImage, outputFileLocation, "jpg");
System.out.println("...Done");
}

public static BufferedImage cropMyImage(BufferedImage img, int cropWidth,
int cropHeight, int cropStartX, int cropStartY) throws Exception {
BufferedImage clipped = null;
Dimension size = new Dimension(cropWidth, cropHeight);

createClip(img, size, cropStartX, cropStartY);

try {
int w = clip.width;
int h = clip.height;

System.out.println("Crop Width " + w);
System.out.println("Crop Height " + h);
System.out.println("Crop Location " + "(" + clip.x + "," + clip.y
+ ")");

clipped = img.getSubimage(clip.x, clip.y, w, h);

System.out.println("Image Cropped. New Image Dimension: "
+ clipped.getWidth() + "w X " + clipped.getHeight() + "h");
} catch (RasterFormatException rfe) {
System.out.println("Raster format error: " + rfe.getMessage());
return null;
}
return clipped;
}

/**
* This method crops an original image to the crop parameters provided.
*
* If the crop rectangle lies outside the rectangle (even if partially),
* adjusts the rectangle to be included within the image area.
*
* @param img = Original Image To Be Cropped
* @param size = Crop area rectangle
* @param clipX = Starting X-position of crop area rectangle
* @param clipY = Strating Y-position of crop area rectangle
* @throws Exception
*/
private static void createClip(BufferedImage img, Dimension size,
int clipX, int clipY) throws Exception {
/**
* Some times clip area might lie outside the original image,
* fully or partially. In such cases, this program will adjust
* the crop area to fit within the original image.
*
* isClipAreaAdjusted flas is usded to denote if there was any
* adjustment made.
*/
boolean isClipAreaAdjusted = false;

/**Checking for negative X Co-ordinate**/
if (clipX < 0) {
clipX = 0;
isClipAreaAdjusted = true;
}
/**Checking for negative Y Co-ordinate**/
if (clipY < 0) {
clipY = 0;
isClipAreaAdjusted = true;
}

/**Checking if the clip area lies outside the rectangle**/
if ((size.width + clipX) <= img.getWidth()
&& (size.height + clipY) <= img.getHeight()) {

/**
* Setting up a clip rectangle when clip area
* lies within the image.
*/

clip = new Rectangle(size);
clip.x = clipX;
clip.y = clipY;
} else {

/**
* Checking if the width of the clip area lies outside the image.
* If so, making the image width boundary as the clip width.
*/
if ((size.width + clipX) > img.getWidth())
size.width = img.getWidth() - clipX;

/**
* Checking if the height of the clip area lies outside the image.
* If so, making the image height boundary as the clip height.
*/
if ((size.height + clipY) > img.getHeight())
size.height = img.getHeight() - clipY;

/**Setting up the clip are based on our clip area size adjustment**/
clip = new Rectangle(size);
clip.x = clipX;
clip.y = clipY;

isClipAreaAdjusted = true;

}
if (isClipAreaAdjusted)
System.out.println("Crop Area Lied Outside The Image."
+ " Adjusted The Clip Rectanglen");
}

/**
* This method reads an image from the file
*
* @param fileLocation -- >
*            eg. "C:/testImage.jpg"
* @return BufferedImage of the file read
*/
public static BufferedImage readImage(String fileLocation) {
BufferedImage img = null;
try {
img = ImageIO.read(new File(fileLocation));
System.out.println("Image Read. Image Dimension: " + img.getWidth()
+ "w X " + img.getHeight() + "h");
} catch (IOException e) {
e.printStackTrace();
}
return img;
}

/**
* This method writes a buffered image to a file
*
* @param img -- > BufferedImage
* @param fileLocation --> e.g. "C:/testImage.jpg"
* @param extension --> e.g. "jpg","gif","png"
*/
public static void writeImage(BufferedImage img, String fileLocation,
String extension) {
try {
BufferedImage bi = img;
File outputfile = new File(fileLocation);
ImageIO.write(bi, extension, outputfile);
} catch (IOException e) {
e.printStackTrace();
}
}

/*
* SANJAAL CORPS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
* SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SANJAAL CORPS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
* MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*
* THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
* CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
* PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
* NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
* SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
* SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
* PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
* SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
* HIGH RISK ACTIVITIES.
*/

}

Here is the output of this program:

Reading Original File : C:/temp/myImage02.jpg
Image Read. Image Dimension: 200w X 370h
Crop Width 150
Crop Height 150
Crop Location (50,50)
Image Cropped. New Image Dimension: 150w X 150h
Writing the cropped image to: C:/temp/myImage-cropped.jpg
...Done

Here is the original Picture:

Here is the picture cropped by the program above.