Image demo : Image « 2D Graphics GUI « Java

Home
Java
1.2D Graphics GUI
2.2D Graphics GUI1
3.3D
4.Advanced Graphics
5.Ant
6.Apache Common
7.Chart
8.Class
9.Collections Data Structure
10.Data Type
11.Database SQL JDBC
12.Design Pattern
13.Development Class
14.EJB3
15.Email
16.Event
17.File Input Output
18.Game
19.Generics
20.GWT
21.Hibernate
22.I18N
23.J2EE
24.J2ME
25.JDK 6
26.JNDI LDAP
27.JPA
28.JSP
29.JSTL
30.Language Basics
31.Network Protocol
32.PDF RTF
33.Reflection
34.Regular Expressions
35.Scripting
36.Security
37.Servlets
38.Spring
39.Swing Components
40.Swing JFC
41.SWT JFace Eclipse
42.Threads
43.Tiny Application
44.Velocity
45.Web Services SOA
46.XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
SCJP
Java » 2D Graphics GUI » ImageScreenshots 
Image demo
Image demo
      

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Label;
import java.awt.MediaTracker;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.color.ColorSpace;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ColorConvertOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.awt.image.LookupOp;
import java.awt.image.RescaleOp;
import java.awt.image.ShortLookupTable;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import javax.swing.JPanel;
import javax.swing.text.Utilities;

public class Sampler extends Frame {
  private Frame mImageFrame;

  private SplitImageComponent mSplitImageComponent;

  private Hashtable mOps;

  public static void main(String[] args) {
    String imageFile = "largeJava2sLogo.jpg";
    if (args.length > 0)
      imageFile = args[0];
    new Sampler(imageFile);
  }

  public Sampler(String imageFile) {
    super();
    createOps();
    createImageFrame(imageFile);
    createUI();
    setVisible(true);
  }

  private void createOps() {
    mOps = new Hashtable();
    createConvolutions();
    createTransformations();
    createLookups();
    createRescales();
    createColorOps();
  }

  private void createConvolutions() {
    float ninth = 1.0f 9.0f;
    float[] blurKernel = ninth, ninth, ninth, ninth, ninth, ninth, ninth,
        ninth, ninth };
    mOps.put("Blur"new ConvolveOp(new Kernel(33, blurKernel),
        ConvolveOp.EDGE_NO_OP, null));

    float[] edge = 0f, -1f0f, -1f4f, -1f0f, -1f0f };
    mOps.put("Edge detector"new ConvolveOp(new Kernel(33, edge),
        ConvolveOp.EDGE_NO_OP, null));

    float[] sharp = 0f, -1f0f, -1f5f, -1f0f, -1f0f };
    mOps.put("Sharpen"new ConvolveOp(new Kernel(33, sharp)));
  }

  private void createTransformations() {
    AffineTransform at;
    at = AffineTransform.getRotateInstance(Math.PI / 60285);
    mOps.put("Rotate nearest neighbor"new AffineTransformOp(at, null));

    RenderingHints rh = new RenderingHints(
        RenderingHints.KEY_INTERPOLATION,
        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    mOps.put("Rotate bilinear"new AffineTransformOp(at, rh));

    at = AffineTransform.getScaleInstance(.5.5);
    mOps.put("Scale .5, .5"new AffineTransformOp(at, null));

    at = AffineTransform.getRotateInstance(Math.PI / 6);
    mOps.put("Rotate bilinear (origin)"new AffineTransformOp(at, rh));
  }

  private void createLookups() {
    short[] brighten = new short[256];
    short[] betterBrighten = new short[256];
    short[] posterize = new short[256];
    short[] invert = new short[256];
    short[] straight = new short[256];
    short[] zero = new short[256];
    for (int i = 0; i < 256; i++) {
      brighten[i(short) (128 + i / 2);
      betterBrighten[i(short) (Math.sqrt((doublei / 255.0255.0);
      posterize[i(short) (i - (i % 32));
      invert[i(short) (255 - i);
      straight[i(shorti;
      zero[i(short0;
    }
    mOps.put("Brighten"new LookupOp(new ShortLookupTable(0, brighten),
        null));
    mOps.put("Better Brighten"new LookupOp(new ShortLookupTable(0,
        betterBrighten)null));
    mOps.put("Posterize"new LookupOp(new ShortLookupTable(0, posterize),
        null));
    mOps.put("Invert"new LookupOp(new ShortLookupTable(0, invert)null));

    short[][] redOnly = invert, straight, straight };
    short[][] greenOnly = straight, invert, straight };
    short[][] blueOnly = straight, straight, invert };
    mOps.put("Red invert"new LookupOp(new ShortLookupTable(0, redOnly),
        null));
    mOps.put("Green invert"new LookupOp(
        new ShortLookupTable(0, greenOnly)null));
    mOps.put("Blue invert"new LookupOp(new ShortLookupTable(0, blueOnly),
        null));

    short[][] redRemove = zero, straight, straight };
    short[][] greenRemove = straight, zero, straight };
    short[][] blueRemove = straight, straight, zero };
    mOps.put("Red remove"new LookupOp(new ShortLookupTable(0, redRemove),
        null));
    mOps.put("Green remove"new LookupOp(new ShortLookupTable(0,
        greenRemove)null));
    mOps.put("Blue remove"new LookupOp(
        new ShortLookupTable(0, blueRemove)null));
  }

  private void createRescales() {
    mOps.put("Rescale .5, 0"new RescaleOp(.5f0null));
    mOps.put("Rescale .5, 64"new RescaleOp(.5f64null));
    mOps.put("Rescale 1.2, 0"new RescaleOp(1.2f0null));
    mOps.put("Rescale 1.5, 0"new RescaleOp(1.5f0null));
  }

  private void createColorOps() {
    mOps.put("Grayscale"new ColorConvertOp(ColorSpace
        .getInstance(ColorSpace.CS_GRAY)null));
  }

  private void createImageFrame(String imageFile) {
    // Create the image frame.
    mSplitImageComponent = new SplitImageComponent(imageFile);
    mImageFrame = new Frame(imageFile);
    mImageFrame.setLayout(new BorderLayout());
    mImageFrame.add(mSplitImageComponent, BorderLayout.CENTER);
//    Utilities.sizeContainerToComponent(mImageFrame, mSplitImageComponent);
  //  Utilities.centerFrame(mImageFrame);
    mImageFrame.setVisible(true);
  }

  private void createUI() {
    setFont(new Font("Serif", Font.PLAIN, 12));
    setLayout(new BorderLayout());
    // Set our location to the left of the image frame.
    setSize(200350);
    Point pt = mImageFrame.getLocation();
    setLocation(pt.x - getSize().width, pt.y);

    final Checkbox accumulateCheckbox = new Checkbox("Accumulate"false);
    final Label statusLabel = new Label("");

    // Make a sorted list of the operators.
    Enumeration e = mOps.keys();
    Vector names = new Vector();
    while (e.hasMoreElements())
      names.addElement(e.nextElement());
    Collections.sort(names);
    final java.awt.List list = new java.awt.List();
    for (int i = 0; i < names.size(); i++)
      list.add((Stringnames.elementAt(i));
    add(list, BorderLayout.CENTER);

    // When an item is selected, do the corresponding transformation.
    list.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent ie) {
        if (ie.getStateChange() != ItemEvent.SELECTED)
          return;
        String key = list.getSelectedItem();
        BufferedImageOp op = (BufferedImageOpmOps.get(key);
        BufferedImage source = mSplitImageComponent.getSecondImage();
        boolean accumulate = accumulateCheckbox.getState();
        if (source == null || accumulate == false)
          source = mSplitImageComponent.getImage();
        String previous = mImageFrame.getTitle() " + ";
        if (accumulate == false)
          previous = "";
        mImageFrame.setTitle(previous + key);
        statusLabel.setText("Performing " + key + "...");
        list.setEnabled(false);
        accumulateCheckbox.setEnabled(false);
        BufferedImage destination = op.filter(source, null);
        mSplitImageComponent.setSecondImage(destination);
        mSplitImageComponent.setSize(mSplitImageComponent
            .getPreferredSize());
        mImageFrame.setSize(mImageFrame.getPreferredSize());
        list.setEnabled(true);
        accumulateCheckbox.setEnabled(true);
        statusLabel.setText("Performing " + key + "...done.");
      }
    });

    Button loadButton = new Button("Load...");
    loadButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent ae) {
        FileDialog fd = new FileDialog(Sampler.this);
        fd.show();
        if (fd.getFile() == null)
          return;
        String path = fd.getDirectory() + fd.getFile();
        mSplitImageComponent.setImage(path);
        mSplitImageComponent.setSecondImage(null);
//        Utilities.sizeContainerToComponent(mImageFrame,
  //          mSplitImageComponent);
        mImageFrame.validate();
        mImageFrame.repaint();
      }
    });

    Panel bottom = new Panel(new GridLayout(21));
    Panel topBottom = new Panel();
    topBottom.add(accumulateCheckbox);
    topBottom.add(loadButton);
    bottom.add(topBottom);
    bottom.add(statusLabel);
    add(bottom, BorderLayout.SOUTH);

    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        mImageFrame.dispose();
        dispose();
        System.exit(0);
      }
    });
  }
  class SplitImageComponent extends JPanel {
    private BufferedImage mImage;

    private BufferedImage mSecondImage;

    private int mSplitX;

    public SplitImageComponent(String path) {
      setImage(path);
      init();
    }

    public SplitImageComponent(BufferedImage image) {
      setImage(image);
      init();
    }

    public void setImage(String path) {
      Image image = blockingLoad(path);
      mImage = makeBufferedImage(image);
    }

    public void setImage(BufferedImage image) {
      mImage = image;
    }

    public void setSecondImage(BufferedImage image) {
      mSecondImage = image;
      repaint();
    }

    public BufferedImage getImage() {
      return mImage;
    }

    public BufferedImage getSecondImage() {
      return mSecondImage;
    }

    private void init() {
      setBackground(Color.white);
      addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent me) {
          mSplitX = me.getX();
          repaint();
        }
      });
      addMouseMotionListener(new MouseMotionAdapter() {
        public void mouseDragged(MouseEvent me) {
          mSplitX = me.getX();
          repaint();
        }
      });
    }

    public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2Dg;
      int width = getSize().width;
      int height = getSize().height;

      // Explicitly clear the window.
      Rectangle clear = new Rectangle(00, width, height);
      g2.setPaint(getBackground());
      g2.fill(clear);
      // Clip the first image, if appropriate,
      // to be on the right side of the split.
      if (mSplitX != && mSecondImage != null) {
        Rectangle firstClip = new Rectangle(mSplitX, 0, width - mSplitX,
            height);
        g2.setClip(firstClip);
      }
      g2.drawImage(getImage()00null);

      if (mSplitX == || mSecondImage == null)
        return;

      Rectangle secondClip = new Rectangle(00, mSplitX, height);
      g2.setClip(secondClip);
      g2.drawImage(mSecondImage, 00null);

      Line2D splitLine = new Line2D.Float(mSplitX, 0, mSplitX, height);
      g2.setClip(null);
      g2.setColor(Color.white);
      g2.draw(splitLine);
    }

    public Dimension getPreferredSize() {
      int width = getImage().getWidth();
      int height = getImage().getHeight();
      if (mSecondImage != null) {
        width = Math.max(width, mSecondImage.getWidth());
        height = Math.max(height, mSecondImage.getHeight());
      }
      return new Dimension(width, height);
    }
  }
  private Component sComponent = new Component() {
  };

  private final MediaTracker sTracker = new MediaTracker(sComponent);

  private int sID = 0;

  public boolean waitForImage(Image image) {
    int id;
    synchronized (sComponent) {
      id = sID++;
    }
    sTracker.addImage(image, id);
    try {
      sTracker.waitForID(id);
    catch (InterruptedException ie) {
      return false;
    }
    if (sTracker.isErrorID(id))
      return false;
    return true;
  }

  public Image blockingLoad(String path) {
    Image image = Toolkit.getDefaultToolkit().getImage(path);
    if (waitForImage(image== false)
      return null;
    return image;
  }

  public Image blockingLoad(URL url) {
    Image image = Toolkit.getDefaultToolkit().getImage(url);
    if (waitForImage(image== false)
      return null;
    return image;
  }

  public BufferedImage makeBufferedImage(Image image) {
    return makeBufferedImage(image, BufferedImage.TYPE_INT_RGB);
  }
  public BufferedImage makeBufferedImage(Image image, int imageType) {
    if (waitForImage(image== false)
      return null;

    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
        image.getHeight(null), imageType);
    Graphics2D g2 = bufferedImage.createGraphics();
    g2.drawImage(image, null, null);
    return bufferedImage;
  }
  
}

           
         
    
    
    
    
    
  
Related examples in the same category
1.Image size Image size
2.Getting the Color Model of an Image
3.Filtering the RGB Values in an Image
4.Create a filter that can modify any of the RGB pixel values in an image.
5.This filter removes all but the red values in an image
6.Load and draw image
7.Paint an IconPaint an Icon
8.Image Processing: Brightness and ContrastImage Processing: Brightness and Contrast
9.Image with mouse drag and move eventImage with mouse drag and move event
10.Image Animation and ThreadImage Animation and Thread
11.Image Color Gray EffectImage Color Gray Effect
12.Image BufferingImage Buffering
13.Image Effect: CombineImage Effect: Combine
14.AffineTransform demoAffineTransform demo
15.Image Effect: Rotate Image using DataBufferImage Effect: Rotate Image using DataBuffer
16.Image Effect: Sharpen, blurImage Effect: Sharpen, blur
17.Image scale
18.Image crop
19.Demonstrating the Drawing of an Image with a Convolve Operation
20.Demonstrating Use of the Image I/O Library
21.Adding Image-Dragging Behavior
22.Sending Image Objects through the ClipboardSending Image Objects through the Clipboard
23.Anti AliasAnti Alias
24.Image OperationsImage Operations
25.Image ViewerImage Viewer
26.Get the dimensions of the image; these will be non-negative
27.Standalone Image Viewer - works with any AWT-supported format
28.Toolkit.getImage() which works the same in either Applet or Application
29.Double Buffered Image
30.Graband Fade: displays image and fades to black
31.Graband Fade with Rasters
32.Rotate Image 45 Degrees
33.Convert java.awt.image.BufferedImage to java.awt.Image
34.Filter image by multiplier its red, green and blue color
35.Drags within the imageDrags within the image
36.TYPE_INT_RGB and TYPE_INT_ARGB are typically used
37.Pixels from a buffered image can be modified
38.Calculation of the mean value of an image with Raster
39.Use PixelGrabber class to acquire pixel data from an Image object
40.Flip an image
41.Rendered Image
42.Image Panel
43.Image Utils
44.Returns an image resource.
45.Create Gradient Image
46.Create Gradient Mask
47.Create Translucent Image
48.Make Raster Writable
49.A frame that displays an image
50.Optimized version of copyData designed to work on Integer packed data with a SinglePixelPackedSampleModel
51.Various image processing operations.Various image processing operations.
52.This program demonstrates the transfer of images between a Java application and the system clipboard.This program demonstrates the transfer of images between a Java application and the system clipboard.
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.