Look down in the createThumbnail method of this for an example from this
little utility I wrote a while back.
/* PictureTour.java
* @author: Charles Bell
* @version: 9/22/2001
*/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/** PictureTour creates an html index page and html web pages which
display all
* the images in the selected directory. Its polls the user to select
any image from
* the folder from which all the image files will be taken to generate
the tour. It
* creates the sub folders called html and thumbnails which contain
the html web pages
* and thumbnailimages generated. When complete it provides the user
with the file URL
* on the last line of the TextArea for the user to copy and paste
into their browser
* url window for easy navigation to the generated index page. Starts
a JEditorPane
* and displays the webpages generated. The user can just click the
pictures or the
* navigation bars to see the results.
*
*/
public class PictureTour implements ActionListener,HyperlinkListener{
JFrame frame;
JTextArea messagebox;
String[] imagenames;
File imagefolder;
File thumbnailfolder;
File htmlfolder;
Vector places;
int defaultimagewidth = 640; //these can be changed here for the
image sizes desired
int defaultimageheight = 480;
int imagewidth = defaultimagewidth;
int imageheight = defaultimageheight;
boolean debug = true;
JEditorPane webeditorpane;
/** Instantiates an instance of this class and initiates it.
*/
public static void main(String[] args){
System.out.println("Starting Java Application PictureTour");
PictureTour tour= new PictureTour();
tour.init();
}
/** Initiates the user interface which is simply just a
JTextArea to display
* what is happening. Its polls the user to select any image
from the folder
* from which all the image files will be taken to generate
the tour. It creates
* the sub folders called html and thumbnails which contain
the html web pages
* and thumbnailimages generated. When complete it provides
the user with the
* file URL on the last line of the TextArea for the user to
copy and paste
* into their browser url window for easy navigation to the
generated index
* page. Starts a JEditorPane and displays the webpages
generated. The user
* can just click the pictures or the navigation bars to see
the results.
*/
public void init(){
frame = new JFrame("PictureTour");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonpanel = new JPanel();
JButton exitbutton = new JButton("Exit");
exitbutton.addActionListener(this);
JButton restartbutton = new JButton("Restart");
restartbutton.addActionListener(this);
buttonpanel.add(exitbutton);
buttonpanel.add(restartbutton);
frame.getContentPane().add(buttonpanel,"North");
messagebox = new JTextArea(20,50);
JScrollPane displaypane = new JScrollPane(messagebox);
frame.getContentPane().add(displaypane,"Center");
frame.pack();
frame.show();
addMessage("Starting Java Application PictureTour.");
imagefolder = getImageFolder();
createSubFolders(imagefolder.getAbsolutePath());
createThumbnails(imagefolder.getAbsolutePath(),thumbnailfolder.getAbsolutePath());
places = new Vector();
imagenames = getImageNames(imagefolder.listFiles(new
FileNameFilter()));
createPlaces(imagenames);
createVirtualTour(imagefolder.listFiles(new
FileNameFilter()));
addMessage("Copying navigation image files to " +
htmlfolder.getName());
copyNavigationImage("TableOfContents.gif");
copyNavigationImage("Previous.gif");
copyNavigationImage("Next.gif");
try{
File start = new File(htmlfolder,"index.html");
addMessage("PictureTour is now complete. To use
it, point your browswer to \n" + start.toURL().toExternalForm());
addMessage("Starting the web page viewer. Click
the links or the pictures.");
show(start.toURL().toExternalForm());
}catch(MalformedURLException murle){
System.out.println("MalformedURLException : " +
murle.getMessage());
}
}
/** Does almost everything init() did except the generic frame
and scroll pane
* initialization. Empties the places vector to start again.
*/
public void restart(){
places.clear();
messagebox.setText("Restarting Java Application
PictureTour\n");
imagefolder = getImageFolder();
createSubFolders(imagefolder.getAbsolutePath());
createThumbnails(imagefolder.getAbsolutePath(),thumbnailfolder.getAbsolutePath());
places = new Vector();
imagenames = getImageNames(imagefolder.listFiles(new
FileNameFilter()));
createPlaces(imagenames);
createVirtualTour(imagefolder.listFiles(new
FileNameFilter()));
addMessage("Copying navigation image files to " +
htmlfolder.getName());
copyNavigationImage("TableOfContents.gif");
copyNavigationImage("Previous.gif");
copyNavigationImage("Next.gif");
try{
File start = new File(htmlfolder,"index.html");
addMessage("PictureTour is now complete. To use
it, point your browswer to \n" + start.toURL().toExternalForm());
addMessage("Starting the web page viewer. Click
the links or the pictures.");
show(start.toURL().toExternalForm());
}catch(MalformedURLException murle){
System.out.println("MalformedURLException : " +
murle.getMessage());
}
}
/** Creates the sub folders called html and thumbnails which
contain the html
* web pages and thumbnailimages generated.
*/
public void createSubFolders(String path){
addMessage("Attempting to create sub folders thumbnail and
html.");
thumbnailfolder = new File(path,"thumbnail");
if (thumbnailfolder.getAbsoluteFile().mkdir()){
addMessage("Created sub folder "
+ thumbnailfolder.getName());
}else{
addMessage("sub folder "
+ thumbnailfolder.getName() + " already exists.");
}
htmlfolder = new File(path,"html");
if (htmlfolder.getAbsoluteFile().mkdir()){
addMessage("Created sub folder " +
htmlfolder.getName());
}else{
addMessage("sub folder " + htmlfolder.getName() +
" already exists.");
}
}
/** Polls the user to select any image from the folder from
which all the
* image files will be taken to generate the tour.
*/
public File getImageFolder(){
addMessage("Select a file in the folder where your images
are located.");
FileDialog fd = new FileDialog(frame,"Select a file in the
folder where your images are located", FileDialog.LOAD);
fd.show();
File imagefolder = new File(fd.getDirectory());
addMessage("You selected " + imagefolder.getAbsolutePath());
return imagefolder;
}
/** Creates an array of String values corresponding to all the
* jpg and gif image files in the array imagedirectory.
*/
public String[] getImageNames(File[] imagedirectory){
String[] names = new String[imagedirectory.length];
for (int i = 0;i<imagedirectory.length;i++){
names[i] = imagedirectory[i].getName();
if (debug) System.out.println(names[i]);
}
return names;
}
/** Copies the image file byte for byte to the new PictureTour
html folder.
*/
public void copyNavigationImage(String s){
try{
File filein = new File(s);
DataInputStream dis = new DataInputStream(new
FileInputStream(filein));
File fileout = new File(htmlfolder,s);
DataOutputStream dos = new DataOutputStream(new
FileOutputStream(fileout));
try{
while (true){
byte b = dis.readByte();
dos.writeByte(b);
}
}catch(EOFException eofe){
dos.close();
dis.close();
}
}catch(FileNotFoundException fnfe){
System.out.println("FileNotFoundException: " +
fnfe.getMessage());
}catch(IOException ioe){
System.out.println("IOException: " +
ioe.getMessage());
}
}
/** Creates thumbnail images inthe thumbnails folder
corresponding to the images
* in the imagefolder directory by calling createThumbnail
with the appropriate
* parameters.
*/
public void createThumbnails(String imagefolderpath, String
thumbnailfolderpath){
File imagefolder = new File(imagefolderpath);
File[] imagefile = imagefolder.listFiles(new
FileNameFilter());
for (int i = 0;i< imagefile.length;i++){
addMessage("Creating thumbnail of " + imagefile
[i].getName());
String thumbnailname = imagefile[i].getName();
thumbnailname =
thumbnailname.substring(0,thumbnailname.indexOf(".")) + "thumb.jpg";
File thumbnail = new
File(thumbnailfolderpath,thumbnailname);
createThumbnail(imagefile[i].getAbsoluteFile(),thumbnail.getAbsoluteFile(),60);
}
}
/** Creates a thumbnail image of the inputimage and saves it
to the
* thumbnail file provided.
*/
public void createThumbnail(File imagefile, File thumbnailfile,
int maxDim){
try {
Toolkit toolkit = Toolkit.getDefaultToolkit();
MediaTracker tracker = new MediaTracker(frame);
Image inImage =
toolkit.getImage(imagefile.getAbsolutePath());
tracker.addImage(inImage,1);
try{
tracker.waitForAll();
if (debug) addMessage(imagefile.getName()
+ " found.");
}catch(InterruptedException ie){
System.out.println("InterruptedException:
" + ie.getMessage());
}
// Determine the scale.
double scale = (double)maxDim
/(double)inImage.getHeight(null);
if (inImage.getWidth(null) > inImage.getHeight(null)) {
scale = (double)maxDim/(double)inImage.getWidth(null);
}
// Determine size of new image. One of them should
equal maxDim.
int scaledW = (int)(scale*inImage.getWidth(null));
int scaledH = (int)(scale*inImage.getHeight(null));
// Create an image buffer in which to paint on.
BufferedImage outImage = new
BufferedImage(scaledW, scaledH,BufferedImage.TYPE_INT_RGB);
// Set the scale.
AffineTransform tx = new AffineTransform();
// If the image is smaller than the desired image
size, don't bother scaling.
if (scale < 1.0d) {
tx.scale(scale, scale);
}
// Paint image.
Graphics2D g2d = outImage.createGraphics();
g2d.drawImage(inImage, tx, null);
g2d.dispose();
// JPEG-encode the image and write to file.
if (debug) System.out.println("Creating " +
thumbnailfile.getName());
if (debug) addMessage("Creating " +
thumbnailfile.getName());
OutputStream os = new FileOutputStream(thumbnailfile);
JPEGImageEncoder encoder =
JPEGCodec.createJPEGEncoder(os);
encoder.encode(outImage);
os.close();
if (debug)
System.out.println(thumbnailfile.getName() + " created");
if (debug) addMessage(thumbnailfile.getName() + "
created.");
} catch (IOException e) {
e.printStackTrace();
}
}
/** Creates and puts objects of type Place into a Vector
called places
* so they can be read back out later when the picture tour
is generated.
*/
public void createPlaces(String[] names){
for (int placenumber = 0;placenumber <
names.length;placenumber++){
String imagefilename = names[placenumber];
String name =
imagefilename.substring(0,imagefilename.indexOf("."));
String thumbnailfilename = name + "thumb.JPG";
Integer p = new Integer(placenumber);
Place nextplace = new Place();
nextplace.name = name;
nextplace.imagefilename = imagefilename;
nextplace.thumbnailfilename = thumbnailfilename;
places.add(nextplace);
if (debug) System.out.println("place.name: " +
nextplace.name);
if (debug)
System.out.println("place.imagefilename: " + nextplace.imagefilename);
if (debug)
System.out.println("place.thumbnailfilename: " + nextplace.thumbnailfilename);
}
if (debug) System.out.println("Sorting the vector places.");
sortPlaces(places);
}
/** Sorts the vector consisiting of objects of type Place by
Place.name.
*/
private void sortPlaces(Vector v){
int k = 0;
int n = v.size();
while (k != n-1){
int j = getSmallestPlace(v,k);
exchange(v,k,j);
k++;
}
}
/** Gets the smallest element of Vector v consisting of Place
objects
* by Place.name.
*/
private int getSmallestPlace(Vector v, int k){
if ((v == null) || (v.size()== k)){
return -1;
}
int i;
int small;
i = k + 1;
small = k;
while (i != v.size()){
Place current = (Place) v.elementAt(i);
Place smallest = (Place) v.elementAt(small);
if
(current.name.compareToIgnoreCase(smallest.name) < 0){
small = i;
}
i++;
}
return small;
}
/** Exchanges element k and j in vector v.
*/
private void exchange (Vector v, int k, int j){
Object o = v.elementAt(k);
v.setElementAt(v.elementAt(j),k);
v.setElementAt(o,j);
}
/** Appends the string to the text area messagebox, and sets
the caret
* position to the end of the text.
*/
private void addMessage(String s){
messagebox.append(s + "\n");
messagebox.setCaretPosition(messagebox.getText().length());
}
/** Creates the html files for the Virtual Tour in the html
subfolder of the
* image folder. It creates an index page called index.html
which contains
* links to all the individual image pages. The user can
click on the navigation
* links provided or can just click on the pictures and it
will automatically
* advance to the next pricture starting over when at the end.
*/
public void createVirtualTour(File[] filedirectory){
//check the screen dimension and adjust the size of the
images displayed
//on the html pages produced if necessary
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int screenwidth = d.width;
int screenheight = d.height;
int screenresolution =
Toolkit.getDefaultToolkit().getScreenResolution();
if (debug) System.out.println("width: " + screenwidth);
if (debug) System.out.println("height: " + screenheight);
if (debug) System.out.println("resolution: " + screenheight);
int useablescreenheight = screenheight*6/10;
if (imageheight > useablescreenheight){
//must multiply by 100 since doing integer math
with fractions
int factor = useablescreenheight *100 / imageheight;
imageheight = imageheight * factor /100; //now
divide by the 100
imagewidth = imagewidth * factor /100;
}
try{
int placenumber = filedirectory.length;
String virtualtourname = imagefolder.getName();
String indexpagename = "index.html";
String htmlfoldername = htmlfolder.getAbsolutePath();
File indexfile = new
File(htmlfoldername,indexpagename);
if (debug) System.out.println("Generating
index.html");
addMessage("Generating index.html");
FileWriter fwforindex = new FileWriter(indexfile);
fwforindex.write("<!DOCTYPE HTML PUBLIC
\"-//W3C//DTD HTML 4.0 Transitional//EN\">\n");
fwforindex.write("<html>\n");
fwforindex.write("<head><title>" + virtualtourname
+ "</title></head>\n");
fwforindex.write("<body text=\"#FFFFFF\"
bgcolor=\"#000000\" link=\"#FFFF00\" vlink=\"#C0C0C0\" alink=\"#C0FFC0\">\n");
fwforindex.write("<center><h1>" + virtualtourname
+ "</h1></center>\n");
fwforindex.write("<center><h3>Click the links or
the pictures</h3></center>\n");
fwforindex.write(" \n");
fwforindex.write("<table BORDER=5 COLS=3
WIDTH=\"100%\" >\n");
ListIterator iterator = places.listIterator();
placenumber = places.size();
int i = 0;
while (iterator.hasNext()){
Place nextplace = (Place) iterator.next();
String name = nextplace.name;
String imagefilename =
nextplace.imagefilename;
String thumbnailfilename =
nextplace.thumbnailfilename;
int nextlinknumber = i + 1;
if (nextlinknumber == placenumber){
nextlinknumber = 0;
}
Place nextlinkedplace = (Place)
places.elementAt(nextlinknumber);
String nextlinkedplacename =
nextlinkedplace.name + ".html";
int lastlinknumber = i - 1;
if (lastlinknumber == placenumber){
lastlinknumber = 0;
}
if (lastlinknumber < 0){
lastlinknumber = placenumber -1;
}
Place lastlinkedplace = (Place)
places.elementAt(lastlinknumber);
String lastlinkedplacename =
lastlinkedplace.name + ".html";
File htmlfile = new
File(htmlfoldername,name + ".html");
FileWriter fwfornextplace = new
FileWriter(htmlfile);
if (debug) System.out.println("Generating
" + name + ".html");
addMessage("Generating " + name + ".html");
fwfornextplace.write("<!DOCTYPE HTML
PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n");
fwfornextplace.write("<html>\n");
fwfornextplace.write("<head><title>VirtualTour</title></head>\n");
fwfornextplace.write("<body>\n");
fwfornextplace.write("<body
text=\"#FFFFFF\" bgcolor=\"#000000\" link=\"#FFFF00\" vlink=\"#C0C0C0\"
alink=\"#C0FFC0\">\n");
Image nextimage =
Toolkit.getDefaultToolkit().createImage("..\\" + imagefilename);
int width = nextimage.getWidth(frame);
int height = nextimage.getHeight(frame);
if ((width > 0) && (height > 0)){
imagewidth = width;
imageheight = height;
}else{
imagewidth = defaultimagewidth;
imageheight = defaultimageheight;
}
if (debug) System.out.println("width: " +
imagewidth + " height: " + String.valueOf(imageheight));
fwfornextplace.write("<center><a href=\""
+ nextlinkedplacename + "\"> <img SRC=\"..\\" + imagefilename + "\" ALT=\""
+ imagefilename.substring(0,imagefilename.indexOf(".")) + "\" width=" +
String.valueOf(imagewidth) + " height=" + String.valueOf(imageheight) +
"></a></center>" + "\n");
fwfornextplace.write("<br>\n");
fwfornextplace.write(" <big>"
+ imagefilename + "</big><center><a href=\"" + lastlinkedplacename + "\">
<img SRC=\"Previous.gif\"></a>");
fwfornextplace.write("<a href=\"" +
indexpagename + "\"><img SRC=\"TableOfContents.gif\"> </a>");
fwfornextplace.write("<a href=\"" +
nextlinkedplacename + "\"> <img SRC=\"Next.gif\"></a></center>" + " \n");
fwfornextplace.write("<br>\n");
fwfornextplace.write("</body>\n");
fwfornextplace.write("</html>\n");
fwfornextplace.close();
if (i%3 == 0 ){
fwforindex.write("<tr>\n");
}
fwforindex.write("<td>\n");
fwforindex.write("<a href=\"" + name +
".html"+ "\"><img SRC=\"..\\thumbnail\\" + thumbnailfilename + "\" width=60
height=45></a><a href=\"" + name + ".html"+ "\"><br>" + name +
"</a><br> " + "\n");
fwforindex.write("</td>\n");
if (i%3 == 2 ){
fwforindex.write("</tr>\n");
}
i++;
}
if (placenumber%3 == 1 ){
fwforindex.write("</tr>\n");
}
if (placenumber%3 == 2 ){
fwforindex.write("<td></td></tr>\n");
}
if (placenumber%3 == 0 ){
fwforindex.write("<td></td><td></td></tr>\n");
}
fwforindex.write("</table>\n");
fwforindex.write("<b><hr>\n");
fwforindex.write("</body>\n");
fwforindex.write("</html>\n");
fwforindex.close();
if (debug) System.out.println("Generated index.html");
addMessage("Generated index.html");
}catch(IOException ioe){
System.out.println("IOException writing file.");
System.out.println(ioe.getMessage());
addMessage("IOException writing file.");
addMessage(ioe.getMessage());
}
}
public void show(String urlstring){
webeditorpane = new JEditorPane();
webeditorpane.addHyperlinkListener(this);
JFrame webframe = new JFrame(urlstring);
JScrollPane scrollpane = new JScrollPane(webeditorpane);
webframe.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
webframe.setContentPane(scrollpane);
webframe.setSize(Toolkit.getDefaultToolkit().getScreenSize());
webframe.show();
try{
webeditorpane.setPage(urlstring);
webeditorpane.setContentType("text/html");
webeditorpane.setEditable(false);
}catch(MalformedURLException murle){
webeditorpane.setContentType("text/html");
webeditorpane.setText("<html><body>MalformedURLException:
" + murle.getMessage() + "<br>Malformed URL: Can not load url: "
+ urlstring + "</body></html>");;
}catch(IOException ioe){
webeditorpane.setContentType("text/html");
webeditorpane.setText("<html><body>IOException: "
+ ioe.getMessage() + "<br>Could not load url: " + urlstring +
"</body></html>");;
}
}
/** Implements ActionListener interface providing action
response to buttons.
*/
public void actionPerformed(ActionEvent actionevent){
String actioncommand = actionevent.getActionCommand();
if (actioncommand.compareTo("Exit") == 0){
System.exit(0);
}
if (actioncommand.compareTo("Restart") == 0){
restart();
}
}
/** Implements HyperlinkListener interface providing capability
for html linking.
*/
public void hyperlinkUpdate(HyperlinkEvent hyperlinkevent){
HyperlinkEvent.EventType eventtype =
hyperlinkevent.getEventType();
URL url = null;
if (eventtype == HyperlinkEvent.EventType.ACTIVATED){
try{
url = hyperlinkevent.getURL();
webeditorpane.setPage(url);
}catch(MalformedURLException murle){
webeditorpane.setContentType("text/html");
webeditorpane.setText("<html><body>MalformedURLException:
" + murle.getMessage() + "<br>Malformed URL: Can not load url: "
+ url.toExternalForm() + "</body></html>");;
}catch(IOException ioe){
webeditorpane.setContentType("text/html");
webeditorpane.setText("<html><body>IOException:
" + ioe.getMessage() + "<br>Could not load url: " + url.toExternalForm() +
"</body></html>");;
}
}
}
//inner classes
/** For the picture file filter.
*/
class FileNameFilter implements FileFilter{
public boolean accept(File file){
boolean status = false;
String filename = file.getName().toLowerCase();
if (((filename.indexOf("jpg") > 0) ||
(filename.indexOf("gif") > 0) ) && (filename.indexOf("thumb")== -1)){
status = true;
}
return status;
}
}
/* Each picture on the tour corresponds to a place with a
filename for the
* and its thumbnail, and a picture name. Created a simple
object to hold
* the data.
*/
class Place{
String name;
String imagefilename;
String thumbnailfilename;
}
}
At 05:30 PM 4/21/2002 -0400, you wrote:
>Hi,
>This might be a dumb question but can anyone tell me how I could convert a
>java.awt.image object into a java.awt.image.BufferedImage object? I know
>bufferedImage is a subclass of image. I can use the constructor to create
>a default bufferedimage with the width, height and imagetype of the AWT
>Image object. Is it the Raster that holds the actual image or is it the
>SampleModel?
>
>Thanks
>
>
>
>
>__________________________________________________________________
>Your favorite stores, helpful shopping tools and great gift ideas.
>Experience the convenience of buying online with Shop@Netscape!
>http://shopnow.netscape.com/
>
>Get your own FREE, personal Netscape Mail account today at
>http://webmail.netscape.com/
>
>===========================================================================
>To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
>of the message "signoff JAVA3D-INTEREST". For general help, send email to
>[EMAIL PROTECTED] and include in the body of the message "help".
===========================================================================
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff JAVA3D-INTEREST". For general help, send email to
[EMAIL PROTECTED] and include in the body of the message "help".