Engine.java
资源名称:picweb.zip [点击查看]
上传用户:shengda799
上传日期:2007-01-10
资源大小:68k
文件大小:23k
源码类别:
图片显示
开发平台:
Java
- // Engine.java
- //
- // This software is Copyright 1998, 2000, 2001 by Mark Watson.
- // This software may be freely used for any purpose
- // and may be modified for any purpose as long as
- // you agree to the following:
- //
- // 1. Any bug fixes or enhancements that you make must be emailed
- // back to Mark Watson (markw@markwatson.com) for possible
- // inclusion in the source code base that is available at
- // the web site www.markwatson.com (credit will be given
- // to contributers).
- //
- // 2. This copyright notice must be kept with the source code
- // and duplicated if you distribute a modified verison of
- // this software in binary form.
- //
- // 3. You will not re-distribute the source code. Rather, any
- // improvements to this program will be returned to Mark
- // Watson so that there is always one source base at
- // the web site www.markwatson.com (you may freely
- // distribute compiled derived versions of this program
- // without any restrictions as long as this entire
- // copyright notice is reproduced with the application
- // (e.g., in the 'help' or 'about' dialog box).
- //
- // 4. This software may not be used for any illegal purpose.
- //
- // 5. You take all responsibility for the use of this software:
- //
- // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
- // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
- // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- // SUCH DAMAGE.
- // OpenSource contributers: Original program: Mark Watson (markw@markwatson.com)
- //
- // Name Email (optional) + changes
- // ---- --------------------------
- // 3.0 Achille Petrilli Achille.Petrilli@cern.ch (directory pop-up, new fonts, larger icons)
- // 4.1 Tony Allan tony@apms.com.au (sorted files, selectable html filename, saved options)
- // 4.2 Tony Allan tony@apms.com.au (fix .html bug, added height/width to HTML, don't write any
- // entry if the subdirectory doesn't have any images, add option
- // to select if thumbnails are reprocessed)
- // 4.3 Reinout van Schouwen rmvschou@cs.vu.nl (added tables and cleaned up HTML generation)
- // 6.0 Mark Watson: added an option to not generate thumbnail images
- // 7.0 Mark Watson: separated PicWeb.java into two parts: a GUI (PicWeb.java) and and
- // engine to generate thumbnail image files and HTML files (Engine.java)
- import java.applet.*;
- import java.awt.*;
- import java.awt.image.*;
- import java.awt.event.*;
- import java.awt.Image;
- import java.awt.Graphics;
- import java.awt.MediaTracker;
- import java.io.*;
- import java.net.*;
- import java.util.*;
- /**
- * Engine - used by the class PicWeb to produce thumbnail image files and
- * HTML files.
- */
- public class Engine {
- static final boolean DEBUG = false; // used for copious debug printout
- private int quality = 60; // JPEG quality, 0 -> 100
- private static final String version = "7.0";
- private static String iniFile = "picweb.ini";
- /**
- * Used to generate small thumbnail images
- */
- private int s_pixels[] = new int[256];
- private float [] reds= new float[256];
- private float [] greens= new float[256];
- private float [] blues= new float[256];
- private boolean [] trans= new boolean[256];
- /**
- * logo - image viewer for thumbnails on GUI
- */
- private Logo logo;
- /**
- * options - holds all data from the properties file
- */
- private Options options;
- /**
- * for callbacks to the PicWeb application for GUI display
- */
- private PicWeb picweb;
- /** Engine class constructor creates the user interface Panel
- * and initializes a work thread
- */
- public Engine(PicWeb picweb, Logo logo, Options options) {
- this.picweb = picweb;
- this.logo = logo;
- this.options = options;
- }
- /**
- * process - given a root directory, recursively process this directory and all
- * subdirectories
- */
- public String process(String root_dir, Logo logo) {
- options.updateFromFile();
- if (!options.dirSpec.equals(root_dir)) {
- options.dirSpec = root_dir;
- options.ini.put("directory", options.dirSpec);
- try {
- OutputStream out = new BufferedOutputStream(new FileOutputStream(iniFile));
- options.ini.store(out, "Engine (" + version + ") properties (directory change)");
- out.close();
- } catch (IOException e) {
- System.out.println(e);
- e.printStackTrace();
- }
- }
- try {
- ProcessGifs(root_dir, options.indexIfEmpty);
- logo.clear();
- return "Done processing." + nl;
- } catch (IOException e) {
- return "caught an io exception in ProcessGifs" + e.toString() + nl;
- }
- catch (IllegalArgumentException e) {
- return "Invalid directory specified." + nl;
- }
- }
- /** Method ProcessGifs processes an entire directory tree by
- * calling itself recursively.
- */
- final private boolean ProcessGifs(String directory, boolean indexIfEmpty) throws IOException {
- boolean found_image = indexIfEmpty; // (ta 4.2) set initial state depending on indexIfEmpty flag.
- picweb.print("Processing: " + directory + nl);
- File dir = new File(directory);
- if (!dir.isDirectory())
- throw new IllegalArgumentException("no such directory");
- File cwd = dir;
- String[] entries = cwd.list(new GraphicsFileFilter());
- int num = entries.length;
- int countTableColumns = 0; //RMvS
- if (options.ini.getProperty("sort" ,"true").toLowerCase().equals("true")) {
- picweb.print("Sorting directory " + directory + nl);
- for (int i = num; --i>0; ) {
- boolean swapped = false;
- for (int j = 0; j<i; j++) {
- if (entries[j].toString().compareTo(entries[j+1].toString()) > 0) {
- String T = entries[j];
- entries[j] = entries[j+1];
- entries[j+1] = T;
- swapped = true;
- }
- }
- if (!swapped)
- break;
- }
- }
- if (options.skipProcessedDirs) {
- // check to see if this sub-directory already has a 'HTMLFilename' file:
- for (int i=0; i<num; i++) {
- if (entries[i].equals(options.HTMLFilename)) {
- picweb.print(directory + " already has a '" + options.HTMLFilename + "' file" + nl);
- return true; // (ta 4.2) need to include previously processed directories
- }
- }
- }
- // Open HTML output file:
- String fname=directory + fs + options.HTMLFilename;
- if (DEBUG) System.out.println("fname="+fname);
- File out_file = new File(fname);
- try {
- if (out_file.exists()) {
- try { out_file.delete(); }
- catch (SecurityException e) { }
- }
- } catch (Exception e) { e.printStackTrace(); }
- DataOutputStream outs = null;
- File d_f = null;
- try {
- try {
- d_f = new File(fname);
- outs = new DataOutputStream(new FileOutputStream(d_f));
- } catch (Exception e) {
- picweb.print("Error writing HTML file: " + options.HTMLFilename + nl + e + nl);
- return found_image;
- }
- // add a comment to the start of the generated html...
- outs.writeBytes("<HTML>" + nl +"<HEAD>" + nl); // RMvS
- outs.writeBytes("<!-- Picture Web Page Maker(tm) version " +
- version + " www.markwatson.com -->" + nl);
- outs.writeBytes("<!-- File created on " + new Date() + " -->" + nl + nl);
- outs.writeBytes("<TITLE>Thumbnail image overview</TITLE>" + nl );
- outs.writeBytes("</HEAD>" + nl + "<BODY>" + nl ); // RMvS
- String dirName = directory.replace('\','/');
- if (options.ini.getProperty("trimDir" ,"false").toLowerCase().equals("true")) {
- int x = dirName.indexOf('/');
- if (x == -1)
- x = 0;
- outs.writeBytes("<h1>" + options.ini.getProperty("dirText" ,"") +
- dirName.substring(x) + "</h1>" + nl);
- }
- else
- outs.writeBytes("<h1>Directory " + dirName + "</h1>" + nl);
- // Make 2 passes at these files:
- // 1. write out HTML href's to sub-directories
- // 2. write out HTML href's showing mini-files, linked to large graphics files
- // or, if in no thumbnail mode:
- // 2. write out full size images
- for(int i = 0; i < num; i++) {
- String entry_name = entries[i].toString();
- String entry_name1 = entry_name.replace('\','/');
- try {
- File f = new File(cwd, entry_name);
- if (f.isDirectory()) {
- // (ta 4.1) tidy up generated html...
- String dirName1 = directory.replace('\','/');
- if (options.ini.getProperty("trimDir" ,"false").toLowerCase().equals("true")) {
- int y = dirName1.indexOf('/');
- if (y == -1)
- y = 0;
- dirName1 = options.ini.getProperty("subDirText" ,
- options.ini.getProperty("dirText" ,"")) +
- dirName1.substring(y);
- }
- // This is a directory, so add an entry to current HTML file.
- // (ta 4.2) Only write directory entry if there was an image in a sub-directory
- if (ProcessGifs(directory + fs + entry_name, indexIfEmpty)) {
- outs.writeBytes("<a href="" + entry_name1 +
- "/" + options.HTMLFilename +
- "">" + dirName1 +
- "/" + entry_name1 +
- "</a><p>" + nl);
- found_image = true;
- } // Recurse down to handle this directory: (depth first is OK here!)
- }
- } catch (Exception e) {
- System.out.println(e);
- e.printStackTrace();
- }
- }
- // RMvS : create table, align it to center:
- outs.writeBytes("<CENTER> <TABLE BORDER="1" PADDING="2">" + nl);
- for (int i = 0; i < num; i++) {
- String entry_name = entries[i].toString();
- String entry_name1 = entry_name.replace('\','/');
- try {
- File f = new File(cwd, entry_name);
- if (!f.isDirectory() &&
- !entry_name.toLowerCase().endsWith("htm") &&
- !entry_name.toLowerCase().endsWith("html")) {
- Image thumbnail = null;
- if (options.thumbs == true) {
- if (DEBUG) System.out.println("in thumb nail mode");
- if (options.skipProcessedFiles) {
- thumbnail = existingThumbnail(directory + fs + convertName(entry_name));
- if (thumbnail == null)
- thumbnail = newImage(directory + fs + entry_name, 1);
- } else {
- thumbnail = newImage(directory + fs + entry_name, 1);
- }
- // Add a link:
- if (thumbnail != null) {
- if (countTableColumns == 0 && options.thumbs) {
- outs.writeBytes("<TR ALIGN=center VALIGN=middle>" + nl);
- }
- outs.writeBytes("<TD>" +
- "<a href="" + entry_name1 + "">" +
- "<IMG src="" + convertName(entry_name).replace('\', '/') + """ +
- " width="" + thumbnail.getWidth(picweb) + """ +
- " height="" + thumbnail.getHeight(picweb) + """ +
- " border="0"></a>");
- if (options.fileNamesFlag) {
- outs.writeBytes("<BR> <FONT SIZE="-1">" + entry_name1 + "</FONT>" + nl);
- }
- outs.writeBytes("</TD>" + nl); //RMvS : added <TD> and </TD> to output string
- found_image = true; // remember that we actually did something in this directory
- countTableColumns++ ; // RMvS
- if (countTableColumns == 3) {
- outs.writeBytes("</TR>" + nl);
- countTableColumns = 0;
- }
- }
- } else { // no thumbnail mode:
- outs.writeBytes("<IMG src="" + entry_name + """ +
- " border="20">");
- if (options.fileNamesFlag) {
- outs.writeBytes("<BR> <FONT SIZE="-1">" + entry_name1 + "</FONT>" + nl); // (ta 4.2)
- }
- found_image = true; // remember that we actually did something in this directory
- }
- }
- } catch (Exception e) {
- System.out.println(e);
- e.printStackTrace();
- }
- }
- if (countTableColumns != 0) {
- outs.writeBytes("</TR>" + nl);
- }
- outs.writeBytes("</TABLE> </CENTER>" + nl + "</BODY> </HTML>");
- }
- finally {
- if (outs != null) outs.close();
- }
- // (ta 4.2) if we didn't find anything, delete the file and write a message.
- // - Yes I know that this is a very crude way to handle a empty directory!
- if (!found_image) {
- if (d_f != null)
- d_f.delete();
- picweb.print(directory + " did not contain any images." + nl);
- }
- return found_image;
- }
- /**
- * Take an image file name and make a thumbnail name.
- */
- private String convertName(String file_name) {
- return file_name.substring(0, file_name.lastIndexOf('.')) + "_s.jpg";
- }
- /**
- * create an image file
- */
- final private Image newImage(String file_name, int scale_mode) {
- if (DEBUG) System.out.println(" -- entered Engine.newImage("+file_name+", "+scale_mode+")");
- File test_file = new File(file_name);
- if (test_file.isDirectory()) {
- System.out.println(" -- leaving Engine.newImage: error: file is a directory");
- return null;
- }
- int to_width, to_height;
- int image_width, image_height, image_pixels[];
- // read data
- URL url=null;
- try { url = new URL("file", "", file_name); }
- catch (MalformedURLException e) { }
- if (url==null) {
- System.out.println(" -- leaving Engine.newImage: malformed URL");
- return null;
- }
- Image input_image = java.awt.Toolkit.getDefaultToolkit().getImage(url);
- MediaTracker tracker = new MediaTracker(picweb);
- tracker.addImage(input_image, 0);
- // load it all before continuing
- try { tracker.waitForAll(); } catch (InterruptedException e){};
- tracker = null;
- image_width = input_image.getWidth(picweb);
- image_height = input_image.getHeight(picweb);
- if (DEBUG) System.out.println(" -- width of image="+image_width + ", height of image="+image_height);
- image_pixels = new int[image_width * image_height];
- to_width = 60;
- to_height = 60;
- float fact2;
- if (image_width>image_height) {
- fact2=image_width;
- } else {
- fact2=image_height;
- }
- fact2 = 60 / fact2;
- to_width = (int)((float)image_width * fact2);
- to_height= (int)((float)image_height* fact2);
- // Tweak the size of the thumbnails:
- if (options.imageSizeChoice == 0) {
- to_width = (2 * to_width) / 3;
- to_height= (2 * to_height)/ 3;
- }
- if (options.imageSizeChoice == 2) {
- to_width = (3 * to_width) / 2;
- to_height= (3 * to_height)/ 2;
- }
- if (options.imageSizeChoice == 3) {
- to_width = (13 * to_width) / 6;
- to_height= (13 * to_height)/ 6;
- }
- //# Create a PixelGrabber to Get the Pixels of the image and store
- //# them into the image_pixels array
- PixelGrabber pixel_grabber =
- new PixelGrabber(input_image.getSource(), 0, 0,
- image_width, image_height, image_pixels,
- 0, image_width);
- if (DEBUG) System.out.println(" -- after creating pixel grabber");
- try {
- pixel_grabber.grabPixels();
- } catch (InterruptedException e) { }
- pixel_grabber = null;
- if (DEBUG) System.out.println(" -- after grabbing pixels: to_width=" + to_width + ", to_height=" + to_height);
- // resample data
- int
- to_pixels[] = new int[to_width*to_height];
- double
- xscale, yscale;
- // set scale
- xscale = ((double)image_width) / ((double)to_width);
- yscale = ((double)image_height) / ((double)to_height);
- // check mode
- if ( scale_mode != 0 ) { // 1 to 1 scaling
- xscale = java.lang.Math.min(xscale,yscale);
- yscale = xscale;
- }
- int
- from_x, from_y,
- to_index, to_x, to_y;
- for(to_index=0,to_y=0;to_y<to_height;to_y++) {
- from_y = (int)(yscale * to_y);
- for(to_x=0;to_x<to_width;to_x++,to_index++) {
- from_x = (int)(xscale * to_x);
- to_pixels[to_index] = image_pixels[ (from_y * image_width) + from_x];
- }// end for x
- }// end for y
- if (DEBUG) System.out.println(" -- before trying to create new thumbnail image in memory");
- // new image
- Image temp= picweb.createImage(new MemoryImageSource(to_width,to_height,
- to_pixels,0,to_width));
- if (DEBUG) {
- System.out.println(" -- after trying to create new thumbnail image in memory: width=" +
- temp.getWidth(picweb) + ", height=" + temp.getHeight(picweb));
- }
- if (options.showLogo) {
- logo.setImage(temp, to_width, to_height);
- }
- if (DEBUG) System.out.println(" -- after setting the thumbnail image on the GUI");
- // save the image to a new GIF file:
- FileOutputStream os = null;
- File output_file = null;
- try {
- output_file = new File(convertName(file_name));
- os = new FileOutputStream(output_file);
- if (DEBUG) System.out.println(" before creating a new JpegEncoder: os="+os);
- JpegEncoder je = new JpegEncoder(temp, quality, os);
- if (DEBUG) System.out.println(" before doing the compress...");
- je.Compress();
- if (DEBUG) System.out.println(" before closing the file...");
- os.close();
- } catch (Exception e) {
- try { os.close(); } catch (IOException e2) {}
- }
- if (options.verbose)
- picweb.print("Creating: " + output_file.getName() + nl);
- if (DEBUG) System.out.println(" -- leaving Engine.newImage");
- return temp;
- }
- /**
- * used int newImage
- */
- final private Image existingThumbnail(String thumbnail_name) {
- File test_file = new File(thumbnail_name);
- if (test_file.isDirectory())
- return null;
- //System.out.println("test_file.exists(): " + test_file.exists());
- if (!test_file.exists())
- return null;
- // read data
- URL url=null;
- try { url = new URL("file", "", thumbnail_name); }
- catch (MalformedURLException e) {System.out.println(e);}
- if (url==null) { return null; }
- Image thumbnail = java.awt.Toolkit.getDefaultToolkit().getImage(url);
- // not sure if we need a Media Tracker if all we need are dimensions?
- MediaTracker tracker = new MediaTracker(picweb);
- tracker.addImage(thumbnail, 0);
- // load it all before continuing
- try { tracker.waitForAll(); } catch (InterruptedException e){};
- tracker = null;
- int width = thumbnail.getWidth(picweb);
- int height = thumbnail.getHeight(picweb);
- if ((width == -1) && (height == -1))
- return null; // image probably doesn't exist...
- if (options.showLogo) {
- logo.setImage(thumbnail, width, height);
- }
- // (ta 4.2)
- if (options.verbose)
- picweb.print("Using existing: " + test_file.getName() + nl);
- return thumbnail;
- }
- /**
- * accept graphics files and director files (only)
- */
- private class GraphicsFileFilter implements FilenameFilter {
- public GraphicsFileFilter() {
- }
- final public boolean accept(File dir, String name) {
- String s = name.toLowerCase();
- if (s.endsWith("_s.jpg")) return false;
- if (s.endsWith("gif")) return true;
- if (s.endsWith("jpg")) return true;
- if (s.endsWith("bmp")) return true;
- if (s.endsWith("jpeg")) return true;
- if (s.endsWith("htm")) return true;
- if (s.endsWith("html")) return true;
- return (new File(dir, name)).isDirectory();
- }
- }
- /** The 'nl' and 'fs' objects are define for string constants
- * instead of using literal strings in order to pass the
- * "100% Pure" Java certification by Key Labs
- */
- private String nl = System.getProperty("line.separator");
- private String fs = System.getProperty("file.separator");
- }
English
