BufferedImage size

Hi,
I am developing a swing application which needs to be able to draw thousands of lines on the screen. The line count may well reach 200K although many of the lines are very small. I need the ability to scale the lines as required.
Obviously drawing each line at paint time is very time consuming and so I currently draw them to a BufferedImage. This has resulted in a very acceptable image on screen which repaints very fast. However, the image can easily grow in excess of 6000 pixels square. The memory required for this runs at 100 - 150M. If I use transparency this figure is even larger (which I really need to do).
Why does a BufferedImage use so much memory? Is there a way of producing similar results with a much smaller memory use?
One thing to note is that all the lines that are drawn are a single colour and hopefully on a transparent background.
Is there a way of storing an image in a raw form and then performing minimal processing to it at draw time?
Is there a way to improve the speed at which Java draws directly to the screen (greatly).
Thanks in advance for any suggestions.
Dan.

ninja600 wrote:
Hi,
I am developing a swing application which needs to be able to draw thousands of lines on the screen. The line count may well reach 200K although many of the lines are very small. I need the ability to scale the lines as required.
Obviously drawing each line at paint time is very time consuming and so I currently draw them to a BufferedImage. This has resulted in a very acceptable image on screen which repaints very fast. However, the image can easily grow in excess of 6000 pixels square. The memory required for this runs at 100 - 150M. If I use transparency this figure is even larger (which I really need to do).Sounds right to me. Such a large image will produce a large memory footprint.
Why does a BufferedImage use so much memory? It doesn't use any more than any other format.
Is there a way of producing similar results with a much smaller memory use?You could compress the image I suppose, but you'd lose quality and take a hit on performance. I usually only compress and image when I'm saving it to disk.
One thing to note is that all the lines that are drawn are a single colour and hopefully on a transparent background.Well that would certainly compress nice, but not sure that's what you want.
Is there a way of storing an image in a raw form and then performing minimal processing to it at draw time?Not sure what you mean.
Is there a way to improve the speed at which Java draws directly to the screen (greatly).Depends on what you are doing. Have you looked at VolitileImage?

Similar Messages

  • RandomAccessFile and BufferedImage

    Is it possible to put lots of BufferedImage inside a File Using RandomAccessFile?
    If yes, how can i do this? How will be the file, and how to read the file?
    thanks... This is urgent! Please!

    Some formats, like jpeg and especially tiff allow for a series of images in a single file,
    but I don't think that's the case with png. Must your file format be png? If your source images
    are pngs it doesn't necessarily imply that you can't write them out in a different format,
    although there are always potential issues there (transparency, etc...).
    For example, here is a demo that reads four seperate images, writes them to a single file
    and reads them back from that file to display the result.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import javax.swing.*;
    public class IOExample {
        public static void main(String[] args) throws IOException {
            String urlPrefix = "http://www3.us.porsche.com/english/usa/carreragt/modelinformation/experience/desktop/bilder/icon";
            String urlSuffix = "_800x600.jpg";
            int SIZE = 4;
            BufferedImage[] images = new BufferedImage[SIZE];
            for(int i=1; i<=SIZE; ++i)
                images[i-1] = ImageIO.read(new URL(urlPrefix + i + urlSuffix));
            File file = new File("test.jpeg");
            file.delete();
            int count = writeImages(images, file);
            if (count < SIZE)
                throw new IOException("Only " + count + " images written");
            images = null;
            images = readImages(file);
            if (images.length < SIZE)
                throw new IOException("Only " + images.length + " images read");
            display(images);
        public static void display(BufferedImage[] images) {
            JFrame f = new JFrame("IOExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel p = new JPanel(new GridLayout(0,1));
            for(int j=0; j<images.length; ++j) {
                JLabel label = new JLabel(new ImageIcon(images[j]));
                label.setBorder(BorderFactory.createEtchedBorder());
                p.add(label);
            f.getContentPane().add(new JScrollPane(p));
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        //suffix is "jpeg", "gif", "png", etc... according to your service providers
        public static ImageWriter getWriter(String suffix) throws IOException {
            Iterator writers = ImageIO.getImageWritersBySuffix(suffix);
            if (!writers.hasNext())
                throw new IOException("no writers for suffix " + suffix);
            return (ImageWriter) writers.next();
        public static ImageReader getReader(String suffix) throws IOException {
            Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
            if (!readers.hasNext())
                throw new IOException("no reader for suffix " + suffix);
            return (ImageReader) readers.next();
        public static int writeImages(BufferedImage[] sources, File destination) throws IOException {
            if (sources.length == 0) {
                System.out.println("Sources is empty!");
                return 0;
            } else {
                ImageWriter writer = getWriter(getSuffix(destination));
                ImageOutputStream out = ImageIO.createImageOutputStream(destination);
                writer.setOutput(out);
                System.out.println("can write sequence = " + writer.canWriteSequence());
                writer.prepareWriteSequence(null);
                for(int i=0; i<sources.length; ++i)
                    writer.writeToSequence(new IIOImage(sources, null, null), null);
    writer.endWriteSequence();
    return sources.length;
    public static BufferedImage[] readImages(File source) throws IOException {
    ImageReader reader = getReader(getSuffix(source));
    ImageInputStream in = ImageIO.createImageInputStream(source);
    reader.setInput(in);
    ArrayList images = new ArrayList();
    GraphicsConfiguration gc = getDefaultConfiguration();
    try {
    for(int j=0; true; ++j)
    images.add(toCompatibleImage(reader.read(j), gc));
    } catch(IndexOutOfBoundsException e) {
    return (BufferedImage[]) images.toArray(new BufferedImage[images.size()]);
    public static String getSuffix(File file) throws IOException {
    String filename = file.getName();
    int index = filename.lastIndexOf('.');
    if (index == -1)
    throw new IOException("No suffix given for file " + file);
    return filename.substring(1+index);
    //make compatible with gc for faster rendering
    public static BufferedImage toCompatibleImage(BufferedImage image, GraphicsConfiguration gc) {
    int w = image.getWidth(), h = image.getHeight();
    int transparency = image.getColorModel().getTransparency();
    BufferedImage result = gc.createCompatibleImage(w, h, transparency);
    Graphics2D g = result.createGraphics();
    g.drawRenderedImage(image, null);
    g.dispose();
    return result;
    public static GraphicsConfiguration getDefaultConfiguration() {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    return gd.getDefaultConfiguration();
    Another option that always works is to use zip format on your file, and put whatever you want
    into it. The classes in package java.util.zip make this straightforward.

  • How to reduce image size

    Hi All,
    I am reading a tiff file using JAI,By looping the tiff file ,Each page of tiff file , i am storing each page into BufferedImage ,then i am storing it as a PNG file (each page of a tiff file).
    Tiff file is of size 2000X3000 pixels (app).
    PNG images are also of same size.
    now i want to read the png images and display it as a Button image,
    Problem is i want to reduce the size of a PNG image which is of 2000X3000 pixels to 150X200 pixels
    How can i do it
    Please help me out .
    here is my piece of code
                File file = new File("filelocationf");
                SeekableStream s = new FileSeekableStream(file);
                TIFFDecodeParam param = null;
                ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
                nopages=dec.getNumPages();
                for(int i=0;i<nopages;i++)
                    RenderedImage op = dec.decodeAsRenderedImage(i);
                    PlanarImage opi = new NullOpImage(dec.decodeAsRenderedImage(i),null,OpImage.OP_IO_BOUND,null);
                    image=new BufferedImage(op.getWidth(),op.getHeight(),BufferedImage.TYPE_INT_ARGB);
                    image = opi.getAsBufferedImage();
                    ImageIO.write(image,"PNG",new File(fname+".PNG"));
               }Thank u all.

    Thank u Very much for ur reply
    i.e want i want .
    but
    how to save a image by reducing its size.
    means
    ImageIO.write(image,"PNG",new File("filename".PNG"));
    {code}
    the above line of code will create png image of BufferedImage size.
    is it possible to reduce the BufferedImage size befor we write it.
    and also tutorial link abt  "g.drawImage();" method
    Thank u All.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Resizing a rotated BufferedImage

    Hi everybody,
    I am currently developing a graphical figure editor. Users can drop several 'objects' on a JPanel.
    These objects are represented on screen by BufferedImages. The objects are resizable, rotatable
    and movable.
    Rotating is implemented using AffineTransform. This works fine.
    However, imagine one of the objects that has been rotated 90 degrees. Its north face will be facing east in
    the viewport. When a user resizes the object by grabbing the east-side (i.e. the north handle before rotation)
    resize-handle and dragging it to the east it is essentially resizing the object in a northwise direction.
    This means that the height of the object is increased and that its origin (top left point) is decreased. However,
    this will be drawn on screen exactly as stated: the height is increased and the origin is decreased and afterwards
    the image is rotated. All this results in an object with the correct size, but drawn at the wrong location (I draw the
    BufferedImage at the origin-point which was just decreased).
    Might be a long and akward story, so here I will post a small example application which illustrates the behaviour
    of my program. The program shows a BufferedImage. On this image a rectangle is drawn, along with an ellipse that
    indicates the north face of the rectangle. Pressing 'R' results in a rotation of 90 degrees, whereas pressing any
    of the four arrow-keys results in a 5-pixel increase in size. Just pressing R once and then an arrow key will
    illustrate my problem.
    My question is simple: how should I go about resizing (not rescaling, I really want to increase the
    number of paintable pixels for my BufferedImage!) a BufferedImage that's been rotated using AffineTransform.
    Any suggestions are greatly appreciated!
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.image.BufferedImage;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    * Creates a BufferedImage that displays a simple image.
    * This Image will can be rotated 1/2 PI degrees by pressing 'R'.
    * By pressing any of the arrow-keys, the image is resized as if stretching
    * the top of the image. (i.e. in the original, non-rotated, image it
    * simply moves the origin of the image and increases the height).
    public class ImageTest extends JPanel implements KeyListener
       double theta = 0.0; // rotation angle
       Point origin = new Point(50,50); // origin of the image
       Dimension size = new Dimension(100,100); // size of the image
       public static void main(String[] args)
          JFrame mainFrame = new JFrame("Image Tester");
          ImageTest imageTest = new ImageTest();
          mainFrame.getContentPane().add(imageTest);
          mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          mainFrame.setSize(400,400);
          mainFrame.show();
          mainFrame.addKeyListener(imageTest);
       // draw the image on the JPanel
       public void paintComponent(Graphics g)
          super.paintComponent(g);
          // create a BufferedImage and draw something on it (a rectangle)
          BufferedImage image =
             new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
          Graphics g2 = image.createGraphics();
          g2.drawRect(0, 0, size.width - 1, size.height - 1);
          g2.fillOval(size.width / 2, 0, 3, 3); // draw a little 'north' indicator
          g2.dispose();
          // now rotate g
          Graphics2D g2d = (Graphics2D)g;
          g2d.rotate(theta,
                     origin.x + size.width / 2.0,
                     origin.y + size.height / 2.0);
          // and draw the image on the specified origin
          g2d.drawImage(image, origin.x, origin.y, null);
        * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
       public void keyPressed(KeyEvent arg0)
          switch(arg0.getKeyCode())
             case (KeyEvent.VK_R):
                // rotate! add 1 / 2 PI degrees of rotation
                theta += Math.PI / 2;
                repaint();
                break;
             case (KeyEvent.VK_LEFT):
             case (KeyEvent.VK_RIGHT):
             case (KeyEvent.VK_DOWN):
             case (KeyEvent.VK_UP):
                // make the image 5 pixels larger
                origin.y = origin.y - 5;
                size.height += 5;
                repaint();
                break;
        * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
       public void keyReleased(KeyEvent arg0)
        * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
       public void keyTyped(KeyEvent arg0)
    }

    Thanks Olek for your suggestion.
    I took your advice (kind-of) and tried something.
    Now I create a BufferedImage on which I draw a rectangle. The resulting Image is transformed to a rotated version of
    this image. To do so, a new BufferedImage is created based on an AffineTransformOp.
    This resulting (rotated) image is then shown on screen.
    However, it still does not work correctly.
    I have to state that this is a very simplified version of my problem. The original program features 8 resize handles, along with one rotation handle above
    the object. When no rotation has been applied everything works fine (i.e. the object can be resized using the handles). However, if someone uses
    the rotation handle to rotate the object 90 degrees (for example), resizing does no longer work correctly.
    This sample program that I provided intends to mimic the case in which a user is stretching a rectangle to the north (without rotation) and to the
    east (with 90 degrees of rotation). As you can see, if you press the UP-arrow if the object is not rotated, it does exactly what it needs to do:
    stretch to the north (i.e. update the origin and increase the height). If you press R once and then try the UP-arrow again, you see that it still does what it needs to do. However, since I update the origin, the BufferedImage is moving up.
    This all is very logical and the program does exactly what I ask it to do. However, it is not what I want it to do and I do not know how to implement what I really want.
    Maybe someone can sketch some solution to this problem:
    1 - Display a buffered image of size 30 x 30 (with some north-indicator)
    2 - Stretch this image to the north a few pixels
    3 - Rotate the buffered image 90 degrees clockwise around its center (north indicator is pointing east)
    4 - Stretch this image to the east a few pixels (which, I think, corresponds to the operation in 2, but it clearly does not!)
    This might be the little kick I need to set me off in the right direction again. I think I might have been thinking about this too long to see the solution
    myself.
    Listed here is my own updated version of the sample I provided in my first post. Clockwise rotation is still key R, counter clockwise rotation is E,
    stretching the image to the north is UP-arrow and decreasing the image from the north is down (i.e. up and down mimic the case in which a user uses
    the northern resize-handle to resize the image; in case of rotation this northern resize-handle is obviously displayed east or whatever).
    Any help is appreciated as always!
    package test;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    * Creates a BufferedImage that displays a simple image.
    * This Image will can be rotated 1/2 PI degrees by pressing 'R'.
    * By pressing any of the arrow-keys, the image is resized as if stretching
    * the top of the image. (i.e. in the original, non-rotated, image it
    * simply moves the origin of the image and increases the height).
    public class ImageTest extends JPanel implements KeyListener
       double theta = 0.0; // rotation angle
       Point origin = new Point(50,50); // origin of the image drawing
       Dimension size = new Dimension(100,100); // size of the image
       public static void main(String[] args)
          JFrame mainFrame = new JFrame("Image Tester");
          ImageTest imageTest = new ImageTest();
          mainFrame.getContentPane().add(imageTest);
          mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          mainFrame.setSize(400,400);
          mainFrame.show();
          mainFrame.addKeyListener(imageTest);
       public void paintComponent(Graphics g)
          super.paintComponent(g);
          // get the BufferedImage in its rotated version;
          BufferedImage image = getImage();
          // display the image
          g.drawImage(image, origin.x, origin.y, null);
       private BufferedImage getImage()
          BufferedImage result =
             new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
          // draw a nice rectangle
          Graphics g = result.createGraphics();
          g.fillRect(0, 0, size.width, size.height);
          // and a north indicator
          g.setColor(Color.BLACK);
          g.fillOval(size.width / 2 - 3, 0, 6, 6);
          return applyRotation(result);
       private BufferedImage applyRotation(BufferedImage source)
          // create the rotation
          AffineTransform transform =
             AffineTransform.getRotateInstance(
                      theta,
                      source.getWidth() / 2,
                      source.getHeight() / 2);
          // make an Operation to create the new buffered image
          AffineTransformOp transformOp =
             new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
          // create dest image
          BufferedImage dest =
             transformOp.createCompatibleDestImage(source, source.getColorModel());
          // apply the filter
          transformOp.filter(source, dest);
          return dest;     
        * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
       public void keyPressed(KeyEvent arg0)
          int key = arg0.getKeyCode();
          switch(key)
             case KeyEvent.VK_R:
                // rotate clockwise
                theta += Math.PI / 2;
                break;
             case KeyEvent.VK_E:
                // rotate counter-clockwise
                theta -= Math.PI / 2;
                break;
             case KeyEvent.VK_UP:
                // scale up
                origin.y -= 5;
                size.height += 5;
                break;
             case KeyEvent.VK_DOWN:
                // scale down
                origin.y += 5;
                size.height -= 5;
                break;
          repaint();
        * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
       public void keyReleased(KeyEvent arg0)
        * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
       public void keyTyped(KeyEvent arg0)
    }

  • Programming a Pencil Tool on Paint?

    Here's my code for Scribble(a pencil tool) and its superclass Shape. Basically, my program remembers where the mouse has been and draws a line from the previous point to the current point. However, the scribble doesn't show up (occasionally you will see a small line at the very end) I think the problem is that each Scribble object only has one previous and one current. Therefore, there is only 1 line left at the end. How can I correct this?
    Thanks in advance!
    Note: this doesn't run since there are about 5 other classes needed. I guess can post them if you want? xD
    import java.awt.*;
    public class Scribble extends Shape{
         protected Point startpt, endpt;
         protected Point previous, current;
         int count = 0;
        public Scribble(Point start, DrawingCanvas dcanvas){
         super();
         System.out.println("SCRIBBLE CREATED!!!!!!!\n\n");
         startpt = start;
         current = start;
         endpt = start;
         canvas = dcanvas;
         bounds = new Rectangle(start);
        public void resize(Point anchor, Point end){
         super.resize(anchor, end);
         previous = current;
         startpt = anchor;
         current = end;
         endpt = end;
        public void translate(int dx, int dy){
         super.translate(dx, dy);
         previous.translate(dx, dy);
         current.translate(dx, dy);
         startpt.translate(dx, dy);
         endpt.translate(dx, dy);
        public void draw(Graphics g, Rectangle regionToDraw){
              count++;
              System.out.println(count);
         if (!bounds.intersects(regionToDraw)){
             return;
         g.setColor(super.getColor());
         g.drawLine((int)previous.getX(), (int)previous.getY(), (int)current.getX(), (int)current.getY());
         if (isSelected) { // if selected, draw the resizing knobs
                           // along the 4 corners
             Rectangle[] knobs = getKnobRects();
             for (int i = 0; i < knobs.length; i++)
              g.fillRect(knobs.x, knobs[i].y,
                   knobs[i].width, knobs[i].height);
    protected Rectangle[] getKnobRects(){
         Rectangle[] knobs = new Rectangle[2];
         knobs[0] = new Rectangle((int)startpt.getX() - KNOB_SIZE/2,
                        (int)startpt.getY() - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         knobs[1] = new Rectangle((int)endpt.getX() - KNOB_SIZE/2,
                        (int)endpt.getY()- KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         return knobs;
    protected int getKnobContainingPoint(Point pt){
         if (!isSelected) return NONE;
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
         if (knobs[i].contains(pt))
              return i;
         return NONE;
    }import java.awt.*;
    import java.util.*;
    import java.io.*;
    public abstract class Shape implements Serializable, Cloneable{
         private Color color;
    protected Rectangle bounds;
    protected boolean isSelected;
    public DrawingCanvas canvas;
    protected static final int KNOB_SIZE = 6;
    protected static final int NONE = -1;
    protected static final int NW = 0;
    protected static final int SW = 1;
    protected static final int SE = 2;
    protected static final int NE = 3;
         Shape(){
              color = Color.darkGray;
         public Color getColor(){
         return color;
         public Object clone(){
              try{
              Shape copy = (Shape)super.clone();
              copy.setBounds(bounds);
              return copy;
              catch(CloneNotSupportedException c){
                   return null;
         public void setColor(Color newColor){
         color = newColor;
         canvas.repaint();
         /** The "primitive" for all resizing/moving/creating operations that
         * affect the rect bounding box. The current implementation just resets
         * the bounds variable and triggers a re-draw of the union of the old &
         * new rectangles. This will redraw the shape in new size and place and
         * also "erase" if bounds are now smaller than before.
         protected void setBounds(Rectangle newBounds){
              Rectangle oldBounds = bounds;
              bounds = newBounds;
              updateCanvas(oldBounds.union(bounds));
         /** The resize operation is called when first creating a rect, as well as
         * when later resizing by dragging one of its knobs. The two parameters
         * are the points that define the new bounding box. The anchor point
         * is the location of the mouse-down event during a creation operation
         * or the opposite corner of the knob being dragged during a resize
         * operation. The end is the current location of the mouse.
         public void resize(Point anchor, Point end){
              Rectangle newRect = new Rectangle(anchor);
              // creates smallest rectange which
              // includes both anchor & end
              newRect.add(end);
              // reset bounds & redraw affected areas
              setBounds(newRect);
              canvas.repaint();
         /** The translate operation is called when moving a shape by dragging in
         * the canvas. The two parameters are the delta-x and delta-y to move
         * by. Note that either or both can be negative. Create a new rectangle
         * from our bounds and translate and then go through the setBounds()
         * primitive to change it.
         public void translate(int dx, int dy){
              Rectangle newRect = new Rectangle(bounds);
              newRect.translate(dx, dy);
              setBounds(newRect);
              canvas.repaint();
         /** Used to change the selected state of the shape which will require
         * updating the affected area of the canvas to add/remove knobs.
         public void setSelected(boolean newState){
              isSelected = newState;
              // need to erase/add knobs
              // including extent of extended bounds
              updateCanvas(bounds, true);
              canvas.repaint();
         /** The updateCanvas() methods are used when the state has changed
         * in such a way that it needs to be refreshed in the canvas to properly
         * reflect the new settings. The shape should take responsibility for
         * messaging the canvas to properly update itself. The appropriate AWT/JFC
         * way to re-draw a component is to send it the repaint() method with the
         * rectangle that needs refreshing. This will cause an update() event to
         * be sent to the component which in turn will call paint(), where the
         * real drawing implementation goes. See the paint() method in
         * DrawingCanvas to see how it is implemented.
         protected void updateCanvas(Rectangle areaOfChange, boolean enlargeForKnobs){
                   System.out.println("canvas2 updated");
              Rectangle toRedraw = new Rectangle(areaOfChange);
              if (enlargeForKnobs)
              toRedraw.grow(KNOB_SIZE/2, KNOB_SIZE/2);
              canvas.repaint(toRedraw);
         protected void updateCanvas(Rectangle areaOfChange){
                   System.out.println("canvas updated");
              updateCanvas(areaOfChange, isSelected);
              public Rectangle getBounds(){
                   return bounds;
         /** When the DrawingCanvas needs to determine which shape is under
         * the mouse, it asks the shape to determine if a point is "inside".
         * This method should returns true if the given point is inside the
         * region for this shape. For a rectangle, any point within the
         * bounding box is inside the shape.
         public boolean inside(Point pt){
              return bounds.contains(pt);
         /** When needed, we create the array of knob rectangles on demand. This
         * does mean we create and discard the array and rectangles repeatedly.
         * These are small objects, so perhaps it is not a big deal, but
         * a valid alternative would be to store the array of knobs as an
         * instance variable of the Shape and and update the knobs as the bounds
         * change. This means a little more memory overhead for each Shape
         * (since it is always storing the knobs, even when not being used) and
         * having that redundant data opens up the possibility of bugs from
         * getting out of synch (bounds move but knobs didn't, etc.) but you may
         * find that a more appealing way to go. Either way is fine with us.
         * Note this method provides a nice unified place for one override from
         * a shape subclass to substitute fewer or different knobs.
         protected Rectangle[] getKnobRects(){
                   System.out.println("knobs gotten");
              Rectangle[] knobs = new Rectangle[4];
              knobs[NW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
              knobs[SW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[SE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[NE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              return knobs;
         /** Helper method to determine if a point is within one of the resize
         * corner knobs. If not selected, we have no resize knobs, so it can't
         * have been a click on one. Otherwise, we calculate the knob rects and
         * then check whether the point falls in one of them. The return value
         * is one of NW, NE, SW, SE constants depending on which knob is found,
         * or NONE if the click doesn't fall within any knob.
         protected int getKnobContainingPoint(Point pt){
                   System.out.println("resize knobs");
              // if we aren't selected, the knobs
              // aren't showing and thus there are no knobs to check
              if (!isSelected) return NONE;
              Rectangle[] knobs = getKnobRects();
              for (int i = 0; i < knobs.length; i++)
              if (knobs[i].contains(pt))
                   return i;
              return NONE;
         /** Method used by DrawingCanvas to determine if a mouse click is starting
         * a resize event. In order for it to be a resize, the click must have
         * been within one of the knob rects (checked by the helper method
         * getKnobContainingPoint) and if so, we return the "anchor" ie the knob
         * opposite this corner that will remain fixed as the user drags the
         * resizing knob of the other corner around. During the drag actions of a
         * resize, that fixed anchor point and the current mouse point will be
         * passed to the resize method, which will reset the bounds in response
         * to the movement. If the mouseLocation wasn't a click in a knob and
         * thus not the beginning of a resize event, null is returned.
    public Point getAnchorForResize(Point mouseLocation){
              System.out.println("is it a resize?");
    int whichKnob = getKnobContainingPoint(mouseLocation);
    if (whichKnob == NONE) // no resize knob is at this location
    return null;
    Rectangle[] knobs = getKnobRects();
    whichKnob = Math.abs(whichKnob - (int)(knobs.length / 2));
    return (new Point(knobs[whichKnob].x + knobs[whichKnob].width /2,
    knobs[whichKnob].y + knobs[whichKnob].height/2));
    public abstract void draw(Graphics g, Rectangle regionToDraw);

    line left at the end. How can I correct this?java.awt.Polygon (or Polygon2D)
    Here are a few of my thoughts
    #1 There is a Shape interface in core java already, as well as plenty of very useful shapes (Rectangle, Ellipse2D, Area). Shape has some really nice features like contains(...) and intersects(...). By creating a separate class for your Shape objects, you ensure that the two will be incompatible.
    #2 As tempting as it is, it is a bad idea to include a Color with a shape. What if you want it to have more than one Color? What if you want the insides of the shape to be filled by an Image? I just created and posted a class on the java forums called Renderable, which combines a java.awt.Shape with a java.awt.Paint.
    #3 Below is my PaintArea class. It "scribbles" on an Image. Maybe this will give you some ideas. To compile it, you will either have to find my MathUtils class (which I've posted here before) or reimplement the distance and angle methods. There is also a reference to WIndowUtilities... find that or remove it and put the PaintArea in a Frame and do setVisible(true)
    You are welcome to use and modify this code, but please don't change the package and please make sure that you add attribution if you submit this in an academic setting.
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui.ex;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import tjacobs.MathUtils;
    import tjacobs.ui.util.WindowUtilities;
    * PaintArea is a component that you can draw in similar to but
    * much simpler than the windows paint program.
    public class PaintArea extends JComponent {
         private static final long serialVersionUID = 0;
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              public static final long serialVersionUID = 0;
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              private static final long serialVersionUID = 1L;
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {
                        private static final long serialVersionUID = 1L;};
                   //int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        @SuppressWarnings("unused")
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    }

  • How to do implement the FrameAccess.java code in my project

    Iam doing an project in java for inserting the videos into oracle9i and searching the inserted videos using the frames of the videos inserted.I have done the project to insert and search the videos.But i have been asked to put an EXTRACT button to extract all the frames of the video being inserted.Please help me to implement the FrameAccess.java coding in my existing coding.I have pasted my coding(VideoInsert.java) and FrameAccess.java(used to extract frames) coding.
    The VideoInsert.java when executed will contain browse button to choose the video file(only .mpg files) to be inserted into the database.After selecting the file and when we press open button in the Open dialog box,the video will be played in jmf player in a separate window and the filepath of the video will be included in the textbox.Now what i need is,an extract button should be placed and when it is clicked,the frames of the corresponding selected video has to be extracted in the location where the project files are stored i.e.,the FrameAccess.java coding has to be executed.
    Please help me if anyone knows how to implement the above concept.
    VideoInsert.java
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import oracle.sql.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.sql.BLOB ;
    import symantec.itools.multimedia.ImageViewer;
    public class VideoInsert extends javax.swing.JFrame {
        private Connection con;
        private Statement st=null;
        private OracleResultSet rs=null;
        int count=0;
        int count1=0;
        ImageViewer displaywindow = new ImageViewer();
        /** Creates new form VideoInsert */
        public VideoInsert() {
            initComponents();
            imgpane.add(displaywindow);
            try {
                DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                con = DriverManager.getConnection("jdbc:oracle:oci:@","scott","tiger");
                  //con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:FIRST","scott","tiger");
                con.setAutoCommit(false);
                st =con.createStatement();
                rs=(OracleResultSet)st.executeQuery("select max(vid) from browsevideo");
                while (rs.next()) {
                    count = (rs.getInt(1) + 1);
                rs.close();
                st =con.createStatement();
                rs=(OracleResultSet)st.executeQuery("select max(imageno) from browseimage");
                while (rs.next()) {
                    count1 = (rs.getInt(1) + 1);
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            txtvid.setText(String.valueOf(count));
             VideoTypeComboBox.addItem("All");
            VideoTypeComboBox.addItem("Entertainment");
            VideoTypeComboBox.addItem("Sports");
            VideoTypeComboBox.addItem("Animation");
            VideoTypeComboBox.addItem("News");
             VideoTypeComboBox.addItem("Others");
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {//GEN-BEGIN:initComponents
            jLabel1 = new javax.swing.JLabel();
            txtvid = new javax.swing.JTextField();
            jLabel2 = new javax.swing.JLabel();
            txtvidfile = new javax.swing.JTextField();
            jLabel3 = new javax.swing.JLabel();
            txtvidinfo = new javax.swing.JTextField();
            jLabel4 = new javax.swing.JLabel();
            txtimgfile = new javax.swing.JTextField();
            vidbrowse = new javax.swing.JButton();
            imgbrowse = new javax.swing.JButton();
            jLabel5 = new javax.swing.JLabel();
            txtimgcont = new javax.swing.JTextField();
            insert = new javax.swing.JButton();
            imgpane = new javax.swing.JPanel();
            jLabel6 = new javax.swing.JLabel();
            VideoTypeComboBox = new javax.swing.JComboBox();
            getContentPane().setLayout(null);
            setTitle("VideoInsert");
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            jLabel1.setText("Video ID");
            getContentPane().add(jLabel1);
            jLabel1.setBounds(30, 80, 90, 16);
            txtvid.setEditable(false);
            getContentPane().add(txtvid);
            txtvid.setBounds(130, 80, 130, 20);
            jLabel2.setText("VideoFile");
            getContentPane().add(jLabel2);
            jLabel2.setBounds(30, 130, 70, 16);
            getContentPane().add(txtvidfile);
            txtvidfile.setBounds(130, 130, 130, 20);
            jLabel3.setText("VideoInfo");
            getContentPane().add(jLabel3);
            jLabel3.setBounds(30, 180, 80, 16);
            getContentPane().add(txtvidinfo);
            txtvidinfo.setBounds(130, 180, 130, 20);
            jLabel4.setText("TopImage");
            getContentPane().add(jLabel4);
            jLabel4.setBounds(30, 230, 70, 16);
            getContentPane().add(txtimgfile);
            txtimgfile.setBounds(130, 230, 130, 20);
            vidbrowse.setText("Browse");
            vidbrowse.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    vidbrowseActionPerformed(evt);
            getContentPane().add(vidbrowse);
            vidbrowse.setBounds(280, 130, 78, 26);
            imgbrowse.setText("Browse");
            imgbrowse.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    imgbrowseActionPerformed(evt);
            getContentPane().add(imgbrowse);
            imgbrowse.setBounds(280, 230, 78, 26);
            jLabel5.setText("ImageContent");
            getContentPane().add(jLabel5);
            jLabel5.setBounds(30, 280, 80, 16);
            getContentPane().add(txtimgcont);
            txtimgcont.setBounds(130, 280, 130, 20);
            insert.setText("Insert");
            insert.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    insertActionPerformed(evt);
            getContentPane().add(insert);
            insert.setBounds(150, 400, 81, 26);
            imgpane.setLayout(new java.awt.BorderLayout());
            getContentPane().add(imgpane);
            imgpane.setBounds(410, 120, 350, 260);
            jLabel6.setText("Video Type");
            getContentPane().add(jLabel6);
            jLabel6.setBounds(30, 340, 80, 16);
            getContentPane().add(VideoTypeComboBox);
            VideoTypeComboBox.setBounds(130, 340, 130, 25);
            pack();
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setSize(new java.awt.Dimension(800, 600));
            setLocation((screenSize.width-800)/2,(screenSize.height-600)/2);
        }//GEN-END:initComponents
        private void insertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertActionPerformed
            BLOB blb= null;
            PreparedStatement stmt = null;
            OutputStream fout=null;
            File f=null;
            FileInputStream fin=null;
            int bufferSize;
            byte[] buffer=null;
            int bytesRead = -1;
            String sfile1 = txtvidfile.getText();
            String sfile2 = txtimgfile.getText();
            String format=null;
            String format1=null;
            String videoinfo=txtvidinfo.getText();
            String imgcontent=txtimgcont.getText();
            String videoType=(String)VideoTypeComboBox.getSelectedItem();
            if(sfile1.endsWith("avi")) {
                format="avi";
            }else if(sfile1.endsWith("mpg")) {
                format="mpg";
            }else {
                format="mpg";
            if(sfile2.endsWith("jpg")) {
                format1="jpg";
            }else if(sfile2.endsWith("gif")) {
                format1="gif";
            }else {
                format1="jpg";
            if((sfile1.length()>0) && (sfile2.length()>0)) {
                try {
                    stmt=con.prepareStatement(" insert into browsevideo values (?,EMPTY_BLOB(),?,?,?)");
                    stmt.setInt(1,count);
                    stmt.setString(2,format);
                    stmt.setString(3,videoinfo);
                     stmt.setString(4,videoType);
                    stmt.executeUpdate();
                    stmt.close();
                    con.commit();
                }catch(Exception e) {
                    e.printStackTrace();
                try {
                    stmt = con.prepareStatement("Select video FROM browsevideo WHERE vid = ? for update of video");
                    stmt.setInt(1,count);
                    rs = (OracleResultSet)stmt.executeQuery();
                    rs.next();
                    blb = rs.getBLOB("video");
                    fout = blb.getBinaryOutputStream();
                    f = new File(sfile1);
                    fin = new FileInputStream(f);
                    bufferSize = blb.getBufferSize();
                    buffer = new byte[bufferSize];
                    while((bytesRead = fin.read(buffer)) != -1) {
                        fout.write(buffer, 0, bytesRead);
                    fout.flush();
                    fout.close();
                    con.commit();
                    rs.close();
                    stmt.close();
                }catch(Exception e) {
                    e.printStackTrace();
                try {
                    stmt=con.prepareStatement(" insert into browseimage values (?,?,?,EMPTY_BLOB(),?,?,?)");
                    stmt.setInt(1,count);
                    stmt.setInt(2,count1);
                    stmt.setInt(3,count1);
                    stmt.setString(4,imgcontent);
                    stmt.setString(5,format1);
                    stmt.setString(6,videoType);
                    stmt.executeUpdate();
                    stmt.close();
                    con.commit();
                }catch(Exception e) {
                    e.printStackTrace();
                try {
                    stmt = con.prepareStatement("Select image FROM browseimage WHERE imageno = ? for update of image");
                    stmt.setInt(1,count1);
                    rs = (OracleResultSet)stmt.executeQuery();
                    if(rs.next()) {
                        blb = rs.getBLOB("image");
                        fout = blb.getBinaryOutputStream();
                        f = new File(sfile2);
                        fin = new FileInputStream(f);
                        bufferSize = blb.getBufferSize();
                        buffer = new byte[bufferSize];
                        while((bytesRead = fin.read(buffer)) != -1) {
                            fout.write(buffer, 0, bytesRead);
                        fout.flush();
                        fout.close();
                        con.commit();
                        rs.close();
                    stmt.close();
                    count++;
                    count1++;
                    txtimgfile.setText("");
                    txtvidfile.setText("");
                    txtimgcont.setText("");
                    txtvidinfo.setText("");
                    txtvid.setText(String.valueOf(count));
                    JOptionPane.showMessageDialog(this,"Successfuly Completed");
                }catch(Exception e) {
                    e.printStackTrace();
        }//GEN-LAST:event_insertActionPerformed
        private void imgbrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_imgbrowseActionPerformed
            ExampleFileFilter filter1 = new ExampleFileFilter();
            JFileChooser chooser = new JFileChooser();
            filter1.addExtension("jpg");
            filter1.addExtension("gif");
            filter1.setDescription("JPG,GIF Images");
            chooser.setFileFilter(filter1);
            int returnVal = chooser.showOpenDialog(this);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                txtimgfile.setText(chooser.getSelectedFile().getAbsolutePath());
                try{
                        displaywindow.setImageURL(new java.net.URL("file:"+txtimgfile.getText()));
                        displaywindow.setStyle(ImageViewer.IMAGE_SCALED_TO_FIT);
                    }catch(Exception e){
                        e.printStackTrace();
        }//GEN-LAST:event_imgbrowseActionPerformed
        private void vidbrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vidbrowseActionPerformed
           ExampleFileFilter filter2 = new ExampleFileFilter();
           JFileChooser chooser = new JFileChooser();
           filter2.addExtension("avi");
            filter2.addExtension("mpg");
            filter2.setDescription("AVI & MPG Video");
            chooser.setFileFilter(filter2);
            int returnVal = chooser.showOpenDialog(this);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                txtvidfile.setText(chooser.getSelectedFile().getAbsolutePath());
                VideoAudioPlayer vap=new VideoAudioPlayer(txtvidfile.getText());
        }//GEN-LAST:event_vidbrowseActionPerformed
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm
            setVisible(false);
            dispose();
        }//GEN-LAST:event_exitForm
         * @param args the command line arguments
        /*public static void main(String args[]) {
            new VideoInsert().show();
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JButton imgbrowse;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JTextField txtvid;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JTextField txtimgcont;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JPanel imgpane;
        private javax.swing.JButton insert;
        private javax.swing.JComboBox VideoTypeComboBox;
        private javax.swing.JButton vidbrowse;
        private javax.swing.JTextField txtvidfile;
        private javax.swing.JLabel jLabel6;
        private javax.swing.JLabel jLabel5;
        private javax.swing.JTextField txtimgfile;
        private javax.swing.JTextField txtvidinfo;
        // End of variables declaration//GEN-END:variables
    FrameAccess.java
    import java.awt.*;
    import javax.media.*;
    import javax.media.control.TrackControl;
    import javax.media.Format;
    import javax.media.format.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import java.awt.image.*;
    import java.util.*;
    import javax.media.util.*;
    * Sample program to access individual video frames by using a
    * "pass-thru" codec. The codec is inserted into the data flow
    * path. As data pass through this codec, a callback is invoked
    * for each frame of video data.
    public class FrameAccess implements ControllerListener {
         Processor p;
         Object waitSync = new Object();
         boolean stateTransitionOK = true;
         public boolean alreadyPrnt = false;
         * Given a media locator, create a processor and use that processor
         * as a player to playback the media.
         * During the processor's Configured state, two "pass-thru" codecs,
         * PreAccessCodec and PostAccessCodec, are set on the video track.
         * These codecs are used to get access to individual video frames
         * of the media.
         * Much of the code is just standard code to present media in JMF.
         public boolean open(MediaLocator ml) {
              try {
                   p = Manager.createProcessor(ml);
                                } catch (Exception e) {
                   System.err.println(
                        "Failed to create a processor from the given url: " + e);
                   return false;
              p.addControllerListener(this);
              // Put the Processor into configured state.
              p.configure();
              if (!waitForState(Processor.Configured)) {
                   System.err.println("Failed to configure the processor.");
                   return false;
              // So I can use it as a player.
              p.setContentDescriptor(null);
              // Obtain the track controls.
              TrackControl tc[] = p.getTrackControls();
              if (tc == null) {
                   System.err.println(
                        "Failed to obtain track controls from the processor.");
                   return false;
              // Search for the track control for the video track.
              TrackControl videoTrack = null;
              for (int i = 0; i < tc.length; i++) {
                   if (tc.getFormat() instanceof VideoFormat) videoTrack = tc[i];
                   else     tc[i].setEnabled(false);
              if (videoTrack == null) {
                   System.err.println("The input media does not contain a video track.");
                   return false;
              String videoFormat = videoTrack.getFormat().toString();
              Dimension videoSize = parseVideoSize(videoFormat);
              System.err.println("Video format: " + videoFormat);
              // Instantiate and set the frame access codec to the data flow path.
              try {
                   Codec codec[] = { new PostAccessCodec(videoSize)};
                   videoTrack.setCodecChain(codec);
              } catch (UnsupportedPlugInException e) {
                   System.err.println("The process does not support effects.");
              // Realize the processor.
              p.prefetch();
              if (!waitForState(Processor.Prefetched)) {
                   System.err.println("Failed to realise the processor.");
                   return false;
              p.start();
              return true;
         /**parse the size of the video from the string videoformat*/
         public Dimension parseVideoSize(String videoSize){
              int x=300, y=200;
              StringTokenizer strtok = new StringTokenizer(videoSize, ", ");
              strtok.nextToken();
              String size = strtok.nextToken();
              StringTokenizer sizeStrtok = new StringTokenizer(size, "x");
              try{
                   x = Integer.parseInt(sizeStrtok.nextToken());
                   y = Integer.parseInt(sizeStrtok.nextToken());
              } catch (NumberFormatException e){
                   System.out.println("unable to find video size, assuming default of 300x200");
              System.out.println("Image width = " + String.valueOf(x) +"\nImage height = "+ String.valueOf(y));
              return new Dimension(x, y);
         * Block until the processor has transitioned to the given state.
         * Return false if the transition failed.
         boolean waitForState(int state) {
              synchronized (waitSync) {
                   try {
                        while (p.getState() != state && stateTransitionOK)
                             waitSync.wait();
                   } catch (Exception e) {
              return stateTransitionOK;
         * Controller Listener.
         public void controllerUpdate(ControllerEvent evt) {
              if (evt instanceof ConfigureCompleteEvent
                   || evt instanceof RealizeCompleteEvent
                   || evt instanceof PrefetchCompleteEvent) {
                   synchronized (waitSync) {
                        stateTransitionOK = true;
                        waitSync.notifyAll();
              } else if (evt instanceof ResourceUnavailableEvent) {
                   synchronized (waitSync) {
                        stateTransitionOK = false;
                        waitSync.notifyAll();
              } else if (evt instanceof EndOfMediaEvent) {
                   p.close();
                   System.exit(0);
         * Main program
         public static void main(String[] args) {
    //          if (args.length == 0) {
    //               prUsage();
    //               System.exit(0);
    // System.out.print("masoud");
    String url = new String("file:F:\\AVSEQ01.mpg");
              if (url.indexOf(":") < 0) {
                   prUsage();
                   System.exit(0);
              MediaLocator ml;
              if ((ml = new MediaLocator(url)) == null) {
                   System.err.println("Cannot build media locator from: " + url);
                   System.exit(0);
              FrameAccess fa = new FrameAccess();
              if (!fa.open(ml))
                   System.exit(0);
         static void prUsage() {
              System.err.println("Usage: java FrameAccess <url>");
         * Inner class.
         * A pass-through codec to access to individual frames.
         public class PreAccessCodec implements Codec {
              * Callback to access individual video frames.
              void accessFrame(Buffer frame) {
                   // For demo, we'll just print out the frame #, time &
                   // data length.
                   long t = (long) (frame.getTimeStamp() / 10000000f);
                   System.err.println(
                        "Pre: frame #: "
                             + frame.getSequenceNumber()
                             + ", time: "
                             + ((float) t) / 100f
                             + ", len: "
                             + frame.getLength());
              * The code for a pass through codec.
              // We'll advertize as supporting all video formats.
              protected Format supportedIns[] = new Format[] { new VideoFormat(null)};
              // We'll advertize as supporting all video formats.
              protected Format supportedOuts[] = new Format[] { new VideoFormat(null)};
              Format input = null, output = null;
              public String getName() {
                   return "Pre-Access Codec";
              //these dont do anything
              public void open() {}
              public void close() {}
              public void reset() {}
              public Format[] getSupportedInputFormats() {
                   return supportedIns;
              public Format[] getSupportedOutputFormats(Format in) {
                   if (in == null)
                        return supportedOuts;
                   else {
                        // If an input format is given, we use that input format
                        // as the output since we are not modifying the bit stream
                        // at all.
                        Format outs[] = new Format[1];
                        outs[0] = in;
                        return outs;
              public Format setInputFormat(Format format) {
                   input = format;
                   return input;
              public Format setOutputFormat(Format format) {
                   output = format;
                   return output;
              public int process(Buffer in, Buffer out) {
                   // This is the "Callback" to access individual frames.
                   accessFrame(in);
                   // Swap the data between the input & output.
                   Object data = in.getData();
                   in.setData(out.getData());
                   out.setData(data);
                   // Copy the input attributes to the output
                   out.setFlags(Buffer.FLAG_NO_SYNC);
                   out.setFormat(in.getFormat());
                   out.setLength(in.getLength());
                   out.setOffset(in.getOffset());
                   return BUFFER_PROCESSED_OK;
              public Object[] getControls() {
                   return new Object[0];
              public Object getControl(String type) {
                   return null;
         public class PostAccessCodec extends PreAccessCodec {
              // We'll advertize as supporting all video formats.
              public PostAccessCodec(Dimension size) {
                   supportedIns = new Format[] { new RGBFormat()};
                   this.size = size;
              * Callback to access individual video frames.
              void accessFrame(Buffer frame) {
                   // For demo, we'll just print out the frame #, time &
                   // data length.
                   if (!alreadyPrnt) {
                        BufferToImage stopBuffer = new BufferToImage((VideoFormat) frame.getFormat());
                        Image stopImage = stopBuffer.createImage(frame);
                        try {
                             BufferedImage outImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                             Graphics og = outImage.getGraphics();
                             og.drawImage(stopImage, 0, 0, size.width, size.height, null);
                             //prepareImage(outImage,rheight,rheight, null);
                             Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
                             ImageWriter writer = (ImageWriter) writers.next();
                             //Once an ImageWriter has been obtained, its destination must be set to an ImageOutputStream:
                             File f = new File(frame.getSequenceNumber() + ".jpg");
                             ImageOutputStream ios = ImageIO.createImageOutputStream(f);
                             writer.setOutput(ios);
                             //Finally, the image may be written to the output stream:
                             //BufferedImage bi;
                             //writer.write(imagebi);
                             writer.write(outImage);
                             ios.close();
                        } catch (IOException e) {
                             System.out.println("Error :" + e);
                   //alreadyPrnt = true;
                   long t = (long) (frame.getTimeStamp() / 10000000f);
                   System.err.println(
                        "Post: frame #: "
                             + frame.getSequenceNumber()
                             + ", time: "
                             + ((float) t) / 100f
                             + ", len: "
                             + frame.getLength());
              public String getName() {
                   return "Post-Access Codec";
              private Dimension size;

    check out the java.lang.Runtime and java.lang.Process classes

  • This is how you extract frames from video

    right then, in answer to many posts about how to get the individual frames from video, here is my solution. it seems to work with mpg files but it doesnt seem to work with any of the avi files i tried. not sure why it doesnt work with those. i have modified javas frame access.
    nothing is displayed except it prints which frame it is doing.
    if anyone wants to improve it, please do. i still dont understand fully how it works so i probably wont be able to answer many questions about it. anyway here it is:
    * @(#)FrameAccess.java 1.5 01/03/13
    * Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
    * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
    * modify and redistribute this software in source and binary code form,
    * provided that i) this copyright notice and license appear on all copies of
    * the software; and ii) Licensee does not utilize the software in a manner
    * which is disparaging to Sun.
    * This software is provided "AS IS," without a warranty of any kind. ALL
    * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
    * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
    * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
    * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
    * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
    * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
    * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
    * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
    * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
    * POSSIBILITY OF SUCH DAMAGES.
    * This software is not designed or intended for use in on-line control of
    * aircraft, air traffic, aircraft navigation or aircraft communications; or in
    * the design, construction, operation or maintenance of any nuclear
    * facility. Licensee represents and warrants that it will not use or
    * redistribute the Software for such purposes.
    import java.awt.*;
    import javax.media.*;
    import javax.media.control.TrackControl;
    import javax.media.Format;
    import javax.media.format.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import java.awt.image.*;
    import java.util.*;
    import javax.media.util.*;
    * Sample program to access individual video frames by using a
    * "pass-thru" codec. The codec is inserted into the data flow
    * path. As data pass through this codec, a callback is invoked
    * for each frame of video data.
    public class FrameAccess implements ControllerListener {
         Processor p;
         Object waitSync = new Object();
         boolean stateTransitionOK = true;
         public boolean alreadyPrnt = false;
         * Given a media locator, create a processor and use that processor
         * as a player to playback the media.
         * During the processor's Configured state, two "pass-thru" codecs,
         * PreAccessCodec and PostAccessCodec, are set on the video track.
         * These codecs are used to get access to individual video frames
         * of the media.
         * Much of the code is just standard code to present media in JMF.
         public boolean open(MediaLocator ml) {
              try {
                   p = Manager.createProcessor(ml);
              } catch (Exception e) {
                   System.err.println(
                        "Failed to create a processor from the given url: " + e);
                   return false;
              p.addControllerListener(this);
              // Put the Processor into configured state.
              p.configure();
              if (!waitForState(Processor.Configured)) {
                   System.err.println("Failed to configure the processor.");
                   return false;
              // So I can use it as a player.
              p.setContentDescriptor(null);
              // Obtain the track controls.
              TrackControl tc[] = p.getTrackControls();
              if (tc == null) {
                   System.err.println(
                        "Failed to obtain track controls from the processor.");
                   return false;
              // Search for the track control for the video track.
              TrackControl videoTrack = null;
              for (int i = 0; i < tc.length; i++) {
                   if (tc.getFormat() instanceof VideoFormat) videoTrack = tc[i];
                   else     tc[i].setEnabled(false);
              if (videoTrack == null) {
                   System.err.println("The input media does not contain a video track.");
                   return false;
              String videoFormat = videoTrack.getFormat().toString();
              Dimension videoSize = parseVideoSize(videoFormat);
              System.err.println("Video format: " + videoFormat);
              // Instantiate and set the frame access codec to the data flow path.
              try {
                   Codec codec[] = { new PostAccessCodec(videoSize)};
                   videoTrack.setCodecChain(codec);
              } catch (UnsupportedPlugInException e) {
                   System.err.println("The process does not support effects.");
              // Realize the processor.
              p.prefetch();
              if (!waitForState(Processor.Prefetched)) {
                   System.err.println("Failed to realise the processor.");
                   return false;
              p.start();
              return true;
         /**parse the size of the video from the string videoformat*/
         public Dimension parseVideoSize(String videoSize){
              int x=300, y=200;
              StringTokenizer strtok = new StringTokenizer(videoSize, ", ");
              strtok.nextToken();
              String size = strtok.nextToken();
              StringTokenizer sizeStrtok = new StringTokenizer(size, "x");
              try{
                   x = Integer.parseInt(sizeStrtok.nextToken());
                   y = Integer.parseInt(sizeStrtok.nextToken());
              } catch (NumberFormatException e){
                   System.out.println("unable to find video size, assuming default of 300x200");
              System.out.println("Image width = " + String.valueOf(x) +"\nImage height = "+ String.valueOf(y));
              return new Dimension(x, y);
         * Block until the processor has transitioned to the given state.
         * Return false if the transition failed.
         boolean waitForState(int state) {
              synchronized (waitSync) {
                   try {
                        while (p.getState() != state && stateTransitionOK)
                             waitSync.wait();
                   } catch (Exception e) {
              return stateTransitionOK;
         * Controller Listener.
         public void controllerUpdate(ControllerEvent evt) {
              if (evt instanceof ConfigureCompleteEvent
                   || evt instanceof RealizeCompleteEvent
                   || evt instanceof PrefetchCompleteEvent) {
                   synchronized (waitSync) {
                        stateTransitionOK = true;
                        waitSync.notifyAll();
              } else if (evt instanceof ResourceUnavailableEvent) {
                   synchronized (waitSync) {
                        stateTransitionOK = false;
                        waitSync.notifyAll();
              } else if (evt instanceof EndOfMediaEvent) {
                   p.close();
                   System.exit(0);
         * Main program
         public static void main(String[] args) {
              if (args.length == 0) {
                   prUsage();
                   System.exit(0);
              String url = args[0];
              if (url.indexOf(":") < 0) {
                   prUsage();
                   System.exit(0);
              MediaLocator ml;
              if ((ml = new MediaLocator(url)) == null) {
                   System.err.println("Cannot build media locator from: " + url);
                   System.exit(0);
              FrameAccess fa = new FrameAccess();
              if (!fa.open(ml))
                   System.exit(0);
         static void prUsage() {
              System.err.println("Usage: java FrameAccess <url>");
         * Inner class.
         * A pass-through codec to access to individual frames.
         public class PreAccessCodec implements Codec {
              * Callback to access individual video frames.
              void accessFrame(Buffer frame) {
                   // For demo, we'll just print out the frame #, time &
                   // data length.
                   long t = (long) (frame.getTimeStamp() / 10000000f);
                   System.err.println(
                        "Pre: frame #: "
                             + frame.getSequenceNumber()
                             + ", time: "
                             + ((float) t) / 100f
                             + ", len: "
                             + frame.getLength());
              * The code for a pass through codec.
              // We'll advertize as supporting all video formats.
              protected Format supportedIns[] = new Format[] { new VideoFormat(null)};
              // We'll advertize as supporting all video formats.
              protected Format supportedOuts[] = new Format[] { new VideoFormat(null)};
              Format input = null, output = null;
              public String getName() {
                   return "Pre-Access Codec";
              //these dont do anything
              public void open() {}
              public void close() {}
              public void reset() {}
              public Format[] getSupportedInputFormats() {
                   return supportedIns;
              public Format[] getSupportedOutputFormats(Format in) {
                   if (in == null)
                        return supportedOuts;
                   else {
                        // If an input format is given, we use that input format
                        // as the output since we are not modifying the bit stream
                        // at all.
                        Format outs[] = new Format[1];
                        outs[0] = in;
                        return outs;
              public Format setInputFormat(Format format) {
                   input = format;
                   return input;
              public Format setOutputFormat(Format format) {
                   output = format;
                   return output;
              public int process(Buffer in, Buffer out) {
                   // This is the "Callback" to access individual frames.
                   accessFrame(in);
                   // Swap the data between the input & output.
                   Object data = in.getData();
                   in.setData(out.getData());
                   out.setData(data);
                   // Copy the input attributes to the output
                   out.setFlags(Buffer.FLAG_NO_SYNC);
                   out.setFormat(in.getFormat());
                   out.setLength(in.getLength());
                   out.setOffset(in.getOffset());
                   return BUFFER_PROCESSED_OK;
              public Object[] getControls() {
                   return new Object[0];
              public Object getControl(String type) {
                   return null;
         public class PostAccessCodec extends PreAccessCodec {
              // We'll advertize as supporting all video formats.
              public PostAccessCodec(Dimension size) {
                   supportedIns = new Format[] { new RGBFormat()};
                   this.size = size;
              * Callback to access individual video frames.
              void accessFrame(Buffer frame) {
                   // For demo, we'll just print out the frame #, time &
                   // data length.
                   if (!alreadyPrnt) {
                        BufferToImage stopBuffer = new BufferToImage((VideoFormat) frame.getFormat());
                        Image stopImage = stopBuffer.createImage(frame);
                        try {
                             BufferedImage outImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                             Graphics og = outImage.getGraphics();
                             og.drawImage(stopImage, 0, 0, size.width, size.height, null);
                             //prepareImage(outImage,rheight,rheight, null);
                             Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
                             ImageWriter writer = (ImageWriter) writers.next();
                             //Once an ImageWriter has been obtained, its destination must be set to an ImageOutputStream:
                             File f = new File(frame.getSequenceNumber() + ".jpg");
                             ImageOutputStream ios = ImageIO.createImageOutputStream(f);
                             writer.setOutput(ios);
                             //Finally, the image may be written to the output stream:
                             //BufferedImage bi;
                             //writer.write(imagebi);
                             writer.write(outImage);
                             ios.close();
                        } catch (IOException e) {
                             System.out.println("Error :" + e);
                   //alreadyPrnt = true;
                   long t = (long) (frame.getTimeStamp() / 10000000f);
                   System.err.println(
                        "Post: frame #: "
                             + frame.getSequenceNumber()
                             + ", time: "
                             + ((float) t) / 100f
                             + ", len: "
                             + frame.getLength());
              public String getName() {
                   return "Post-Access Codec";
              private Dimension size;

    The quality of the produced video from this example is very poor.
    It comes to huuuuge surprise the following fact.
    If you comment the line where you set the PostAccessCodec, the chain of the codecs is:
    MPEG-1 decoder -> YUV2RGB -> Direct Draw Renderer. ( The one used from the system to decode and render)
    If you run the example purely as is above you get the following sequence(as long with the poor quality):
    MPEG-1 decoder -> YUV2RGB -> Windows GDI Renderer.
    So you say lets set another Renderer. So
    you add the following line videoTracker.setRenderer( new DDRenderer() )
    What comes to a surprise is the following chain of codecs:
    MPEG-1 decoder -> YUV2RGB -> Post Codec -> Java RGB Converter - > DDRenderer
    The quality now may be perfect but video runs to slow. The surprising thing here is that even though we have set the outputFormat of the PostAccessFrame codec to RGBFormat the system converts it again to RGB through codec Java RGB Format.
    After searching a lot and reaching the conclusion that the deference between the 2 RGB's is their sizes I sudently was brought in front of a method called grabFrame(). Bels started ringing inside my head. Starts were comming up. Looking at the definition of the class com.sun.media.renderer.video.DDRenderer I descovered that this damn class implements the FrameGrabbingControl Interface. What the f.....? The problem that consumed 4 days of my life and multiplied with 10 to give hours has finally come to an and.
    Summing up the solution for grabbing frames is this!!!!!
    DDRenderer renderer = new DDRenderer();
    videoTrack.setRenderer( renderer );
    and in your actionPerformed implementation
    FrameGrabbingControl fr = (FrameGrabbingControl)renderer.getControl( "javax.media.control.FrameGrabbingControl");
    Buffer frame = fr.grabFrame();
    The following stuff ...are stated in FrameAccess
    --Sniper

  • BackGround picture for a Swing application??

    hi,
    once I got a nice idea while watching some webpages. we can give a background picture for a webpage in <body> tag?
    I want to do same thing for any Swing application. Currently I am working on that issue. Any suggestions are welcome!!
    santhosh

    Hi everybody!
    Finally I got it. now Using this We can enable background for any swing application.
    the complete code is shown here. If you have any problems regarding this code, please mail to [email protected]
    /******************************[TexturedImageIcon.java]***********************/
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    /* this is used to generate a tiled image from a given image file.*/
    public class TexturedImageIcon extends ImageIcon
         private Dimension size = new Dimension(10, 10);
         BufferedImage bimg1,bimg;
         Graphics2D g2;
         ComponentListener cl = new ComponentAdapter(){
              public void componentResized(ComponentEvent ce){
                   Component c = (Component)ce.getSource();
                   size = c.getSize();
                   createImage();
         public void setImage(String filename){
              super.setImage(new ImageIcon(filename).getImage());
              bimg1=null;
              createImage();
         public TexturedImageIcon(Component comp, Image img){
              super(img);
              addListener(comp);
         public TexturedImageIcon(Component comp, String filename){
              super(filename);
              addListener(comp);
         public TexturedImageIcon(Component comp, URL url){
              super(url);
              addListener(comp);
         private void addListener(Component comp){
              comp.addComponentListener(cl);
         private void createImage(){
              bimg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
              g2 = bimg.createGraphics();
              Rectangle2D rect = new Rectangle2D.Float(0,0,size.width-1, size.height-1);
              Rectangle2D tr = new Rectangle2D.Double(0,0,super.getIconWidth(), super.getIconHeight());
              if(bimg1==null){
                   bimg1 = new BufferedImage(super.getIconWidth(), super.getIconHeight(), BufferedImage.TYPE_INT_RGB);
                   Graphics2D g = bimg1.createGraphics();
                   g.drawImage(super.getImage(), null, null);
              TexturePaint tp = new TexturePaint(bimg1, tr);
              g2.setPaint(tp);
              g2.fill(rect);
         public int getIconWidth(){ return size.width; }
         public int getIconHeight(){ return size.height; }
         public Image getImage(){
              System.out.println("asked");
              return bimg;
         public void paintIcon(Component c, Graphics g, int x, int y){
              Graphics2D g2d =(Graphics2D)g;
              g2d.drawImage(bimg, null, null);
         public static void main(String[] args){
              JFrame f = new JFrame();
              f.setSize(300,300);
              JLabel label = new JLabel();
              label.setBackground(Color.white);
              label.setBorder(BorderFactory.createRaisedBevelBorder());
              label.setIcon(new TexturedImageIcon(label, "world2.gif"));
              f.getContentPane().setLayout(new BorderLayout());
              f.getContentPane().add(label, BorderLayout.CENTER);
              f.show();
    /*********************************[JFCUtils.java]************************/
    /*The main logic to enable background picture lies in this class*/
    public class JFCUtils{
         public static ContainerListener cl = new ContainerAdapter(){
              public void componentAdded(ContainerEvent ce){
                   JComponent child = (JComponent)ce.getChild();
                   child.setOpaque(false);
                   child.addContainerListener(this);
                   addlisteners(child);
         public static TexturedImageIcon enableBackGround(JFrame f, String filename){
              ((JPanel)f.getContentPane()).setOpaque(false);
              JLayeredPane lp = f.getLayeredPane();
              JLabel label = new JLabel();
              TexturedImageIcon icon = new TexturedImageIcon(label, filename);
              label.setIcon(icon);
              JPanel panel = new JPanel(new BorderLayout());
              panel.add(label, BorderLayout.CENTER);
              lp.add(panel, new Integer(Integer.MIN_VALUE));
              Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
              panel.setBounds(0, 0, screen.width,screen.height);
              addlisteners((JComponent)f.getContentPane());
              return icon;
         private static void addlisteners(Component c){
              c.toString();
              if(c instanceof JComponent) ((JComponent)c).setOpaque(false);
              if(c instanceof Container){
                   Container ct = (Container)c;
                   ct.addContainerListener(cl);          
              for(int i=0; i<ct.getComponentCount(); i++){ //recursivly make all subcomponents transparent
                   Component child = (Component)ct.getComponent(i);
                   addlisteners(child);
         public static void main(String[] args){
              JFrame f = new JFrame();
              enableBackGround(f, "bg.jpg");
              JButton b = new JButton("fdfdfdfd");
              f.getContentPane().add(b, BorderLayout.NORTH);
              f.setSize(300,300);
              f.show();
    /*************************************[UserDialog.java]**************************/
    //to check how a swing application with background looks like
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class UserDialog extends JDialog
         JPanel contents = (JPanel)getContentPane();
         JTextField shortField = new JTextField(20);
         JTextField nameField = new JTextField(20);
         JTextField emailField = new JTextField(20);
         JTextField smtpServerField = new JTextField(20);
         JTextField pwdField = new JPasswordField(20);
         JTextField pwdField1 = new JPasswordField(20);
         boolean okay = false;
         public UserDialog(JFrame owner){
              super(owner, "New User Details", true);
              initComponents();
              pack();
              setResizable(false);
         public UserDialog(JDialog owner){
              super(owner, "New User Details", true);
              initComponents();
              pack();
              setResizable(false);
         private void initComponents(){
              JPanel west = new JPanel(new GridLayout(0, 1));
              west.add(new JLabel("Short Name"));
              west.add(new JLabel("Full Name"));
              west.add(new JLabel("Email"));
              west.add(new JLabel("SMTP Server"));
              west.add(new JLabel("Password"));
              west.add(new JLabel("Confirm Password"));
              JPanel east = new JPanel(new GridLayout(0, 1));
              east.add(shortField);
              east.add(nameField);
              east.add(emailField);
              east.add(smtpServerField);
              east.add(pwdField);
              east.add(pwdField1);
              JPanel south = new JPanel();
              JButton ok = new JButton("Ok");
              JButton cancel = new JButton("Cancel");
              south.add(ok);
              south.add(cancel);
              contents.setBorder(JFCUtils.border);
              contents.setLayout(new BorderLayout(10, 10));
              contents.add(west, BorderLayout.WEST);
              contents.add(east, BorderLayout.EAST);
              contents.add(south, BorderLayout.SOUTH);
              ActionListener al = new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        okay = ae.getActionCommand().equals("Ok");
                        setVisible(false);
              ok.addActionListener(al);
              cancel.addActionListener(al);
         private void clearFields(){
              shortField.setText("");
              nameField.setText("");
              emailField.setText("");
              smtpServerField.setText("");
              pwdField.setText("");
              pwdField1.setText("");
         public User getUser(){
              clearFields();
              okay = false;
              show();
              if(okay) return new User(shortField.getText(), nameField.getText(), emailField.getText(), smtpServerField.getText(), pwdField.getText());
              else return null;
         public static void main(String[] args){
              Dialog dlg = new UserDialog();
              TexturedImageIcon ticon = JFCUtils.enableBackGround(f, "bg.jpg");.show();
              //we can change the background picture by calling ticon.setImage(...) at runtime.

  • Setting the fg/bg color of a 1 bit image

    Is there a simple way to set the foreground and background colors of a one bit image? What I need to do is draw a bitmap on a Canvas component where all black pixels in the loaded (gif) Image paint as my custom foreground color and all white pixels paint as my custom background color. I'm thinking maybe something like drawing a filled rectangle using the bitmap as a mask?? I am porting code from Windows, and this is something that is kind of built in to MFC.
    Currently I have this working in Windows running Java 1.4.0, but it wont work on a Macintosh running Java 1.1 (or 1.2?). I'm wondering if I stumbled upon a quirk that only works in Windows?
    This is the code from my Canvas object paint() method:
    g.drawImage(bitmapUp, 0, 0, getForeground(), this);
    g.setXORMode(getForeground());
    g.drawImage(bitmapUp, 0, 0, getBackground(), this);
    'bitmapUp' is a one color gif image with transparency. Basically anything that is not transparent gets filled with my foreground color. It seems like this is not the best way to go about things (even if it worked on all platforms).
    Test it here if you want:
    http://www.wizardmaster.com/test/muzakaster/
    - Thanks, Markus P.Spanglestein

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class TwoTone {
         static final int SIZE = 200;
         static BufferedImage image = new BufferedImage(SIZE,SIZE,
                   BufferedImage.TYPE_BYTE_BINARY); //Black&White
         public static void main(String[] args) {
              JFrame f = new JFrame("TwoTone");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Graphics2D g2 = image.createGraphics();
              g2.setPaint(Color.WHITE);
              g2.setStroke(new BasicStroke(6f));
              g2.draw(new Ellipse2D.Float(0,0,SIZE, SIZE));
              g2.dispose();
              final JLabel label = new JLabel(new ImageIcon(image));
              label.addMouseListener(new MouseAdapter(){
                   public void mousePressed(MouseEvent evt) {
                        IndexColorModel icm = (IndexColorModel) image.getColorModel();
                        int[] rgbs = new int[2];
                        icm.getRGBs(rgbs);
                        Color c0 = JColorChooser.showDialog(label,
                             "Choose background", new Color(rgbs[0]));
                        Color c1 = JColorChooser.showDialog(label,
                             "Choose foreground", new Color(rgbs[1]));
                        rgbs[0] = c0.getRGB();
                        rgbs[1] = c1.getRGB();
                        icm = new IndexColorModel(1, 2, rgbs, 0, false, -1, DataBuffer.TYPE_BYTE);
                        image = new BufferedImage(icm, image.getRaster(), false, null);
                        label.setIcon(new ImageIcon(image));
              f.getContentPane().add(label);
              f.pack();
              f.show();
    }

  • Nested canvas in GridLayout can't get its width and height

    Hello,
    I have a class entitled DisplayCanvas, which will accept some parameters from an invocation in another class including a shape and message parameters. These parameters must be centered in the instance of DisplayCanvas.
    For some reason, when I use this.getWidth() and this.getHeight() within my DisplayCanvas class, I get 0 and 0! I need the width and height in order to center the parameters the user will enter.
    Why does the width and height result at 0? What can I do to get the width and height?
    In my DisplayCanvas class notice the lines:
    canWidth = this.getWidth();
    canHeight = this.getHeight();
    For some reason the result is 0 for each!
    Here is my code for the DisplayCanvas class:
    //import the necessary clases
    import java.awt.*;
    import java.applet.*;
    import javax.swing.*;
    //begin the DisplayCanvas
    public class DisplayCanvas extends Canvas
      //declare private data members to house the width and height of the canvas
      private int canWidth;
      private int canHeight;
      //declare private data members for the shape and message
      private String message;
      private String shape;
      private Color sColor;
      private int sWidth;
      private int sHeight;
      private String font;
      private Color ftColor;
      private int ftSize;
      //declare public data members
      //constructor of DisplayCanvas
      public DisplayCanvas()
         //set the width and height
         canWidth = this.getWidth();
         canHeight = this.getHeight();
         //set all data members to defaults
         message = "";
         shape = "";
         sColor = null;
         sWidth = 0;
         sHeight = 0;
         font = "";
         ftColor = null;
         ftSize = 0;
      } //end the constructor
      //begin the setParams function
      public void setParams(String m, String s, Color c, int w, int h,
                            String f, Color ftC, int ftS)
          //set all private data members of DisplayShape to the arguments
          //this function assumes error checking was done by DemoShape
          message = m;
          shape = s;
          sColor = c;
          sWidth = w;
          sHeight = h;
          font = f;
          ftColor = ftC;
          ftSize = ftS;
      } //end the setParams function
      //begin the public paint function of ShowShape
      public void paint(Graphics g)
          //set and output the shape according to the arguments
          //determine the x and y of the shape
          int x = (canWidth - sWidth) / 2;
          int y = (canHeight - sHeight) / 2;
          //set the color for the graphic object
          g.setColor(sColor);
          //output the shape
          g.drawRect(x, y, sWidth, sHeight);
          //set and output the message according to the arguments
          //set the color and the font for the graphic object
          g.setColor(ftColor);
          g.setFont(new Font(font, Font.PLAIN, ftSize));
          //determine the centering of the message
          //output the message with the settings
          g.drawString(canWidth + " " + canHeight, 10, 10);
      } //end the paint function of ShowShape class
    } //end the DisplayCanvas classHere is my form entry class using the nested DisplayCanvas instance entitled drawCanvas:
    //import the necessary java packages
    import java.awt.*;                  //for the awt widgets
    import javax.swing.*;               //for the swing widgets
    import java.awt.event.*;            //for the event handler interfaces
    //no import is needed for the DisplayCanvas class
    //if in the same directory as the DemoShape class
    public class DemoShape extends JApplet
        //declare private data members of the DemoShape class
        //declare the entry and display panel containers
        private Container entire;           //houses entryPanel and displayCanvas
        private JPanel entryPanel;          //accepts the user entries into widgets
        private DisplayCanvas drawCanvas;   //displays the response of entries
        //required control buttons for the entryPanel
        private JTextField xShapeText, yShapeText, messageText, fontSizeText;
        private ButtonGroup shapeRadio;
        private JRadioButton rect, oval, roundRect;
        private JComboBox shapeColorDrop, fontTypeDrop, fontColorDrop;
        //declare public data members of the DemoShape class
        //init method to initialize the applet objects
        public void init()
            //arrays of string to be used later in combo boxes
            //some are used more than once
            String fonts[] = {"Dialog", "Dialog Input", "Monospaced",
                                "Serif", "Sans Serif"};
            String shapes[] = {"Rectangle", "Round Rectangle", "Oval"};   
            String colors[] = {"Black", "Blue", "Cyan", "Dark Gray",
                                "Gray", "Green", "Light Gray", "Magenta", "Orange",
                                "Pink", "Red", "White", "Yellow"};
            //declare variables to assist with the layout
            //these are the left and right justified x coordinates
            int ljX = 10; int rjX = 150;
            //this is the y coordinates for the rows
            int yRow1 = 10;     //the shape rows
            int yRow2 = 40;
            int yRow3 = 60;
            int yRow4 = 130;
            int yRow5 = 150;
            int yRow6 = 210;    //the message rows
            int yRow7 = 240;
            int yRow8 = 260;
            int yRow9 = 300;
            int yRow10 = 320;
            int yRow11 = 360;
            int yRow12 = 380;
            //these are the widths for the text boxes, drop downs
            //message entry,  big message entry and radio buttons
            int tWidth = 30; int dWidth = 100;
            int mWidth = 250; int bmWidth = 250;
            int rWidth = 125;
            //the height is universal, even for the messages!
            int height = 25;
            //set a content pane for the entire applet
            //set the size of the entire window and show the entire applet
            entire = this.getContentPane();
            entire.setLayout(new GridLayout(1, 2));
            //create the entry panel and add it to the entire pane
            entryPanel = new JPanel();
            entryPanel.setLayout(null);
            entire.add(entryPanel);
            //create the display canvas and add it to the entire pane
            //this will display the output
            drawCanvas = new DisplayCanvas();
            entire.add(drawCanvas);       
            //entry panel code
            //add the form elements in the form of rows
            //the first row (label)
            JLabel entryLabel = new JLabel("Enter Shape Parameters:");
            entryPanel.add(entryLabel);
            entryLabel.setBounds(ljX, yRow1, bmWidth, height);
            //second row (labels)
            JLabel shapeTypeLabel = new JLabel("Select Shape:");
            shapeTypeLabel.setBounds(ljX, yRow2, mWidth, height);
            entryPanel.add(shapeTypeLabel);
            JLabel shapeColorLabel = new JLabel("Select Shape Color:");
            shapeColorLabel.setBounds(rjX, yRow2, mWidth, height);
            entryPanel.add(shapeColorLabel);
            //third row (entry)        
            rect = new JRadioButton("Rectangle", true);
            oval = new JRadioButton("Oval", false);
            roundRect = new JRadioButton("Round Rectangle", false);
            rect.setBounds(ljX, yRow3, rWidth, height);
            oval.setBounds(ljX, yRow3 + 20, rWidth, height);
            roundRect.setBounds(ljX, yRow3 + 40, rWidth, height);
            shapeRadio = new ButtonGroup();
            shapeRadio.add(rect);
            shapeRadio.add(oval);
            shapeRadio.add(roundRect);
            entryPanel.add(rect);
            entryPanel.add(oval);
            entryPanel.add(roundRect);       
            shapeColorDrop = new JComboBox(colors);
            shapeColorDrop.setBounds(rjX, yRow3, dWidth, height);
            shapeColorDrop.addFocusListener(new focusListen());
            entryPanel.add(shapeColorDrop);
            //the fourth row (labels)
            JLabel xShapeLabel = new JLabel("Enter Width:");
            xShapeLabel.setBounds(ljX, yRow4, mWidth, height);
            entryPanel.add(xShapeLabel);
            JLabel yShapeLabel = new JLabel("Enter Height:");
            yShapeLabel.setBounds(rjX, yRow4, mWidth, height);
            entryPanel.add(yShapeLabel);
            //the fifth row (entry)
            xShapeText = new JTextField("200", 3);
            xShapeText.setBounds(ljX, yRow5, tWidth, height);
            xShapeText.addFocusListener(new focusListen());
            entryPanel.add(xShapeText);        
            yShapeText = new JTextField("200", 3);
            yShapeText.setBounds(rjX, yRow5, tWidth, height);
            yShapeText.addFocusListener(new focusListen());
            entryPanel.add(yShapeText);
            //the sixth row (label)
            JLabel messageLabel = new JLabel("Enter Message Parameters:");
            messageLabel.setBounds(ljX, yRow6, bmWidth, height);
            entryPanel.add(messageLabel);
            //the seventh row (labels)   
            JLabel messageEntryLabel= new JLabel("Enter Message:");
            messageEntryLabel.setBounds(ljX, yRow7, mWidth, height);
            entryPanel.add(messageEntryLabel);
            //the eighth row (entry)
            messageText = new JTextField("Enter your message here.");
            messageText.setBounds(ljX, yRow8, mWidth, height);
            messageText.addFocusListener(new focusListen());
            entryPanel.add(messageText);
            //the ninth row (label)
            JLabel fontTypeLabel = new JLabel("Select Font:");
            fontTypeLabel.setBounds(ljX, yRow9, mWidth, height);
            entryPanel.add(fontTypeLabel);
            JLabel fontColorLabel = new JLabel("Select Font Color:");
            fontColorLabel.setBounds(rjX, yRow9, mWidth, height);
            entryPanel.add(fontColorLabel);
            //the tenth row (entry)
            fontTypeDrop = new JComboBox(fonts);
            fontTypeDrop.setBounds(ljX, yRow10, dWidth, height);
            fontTypeDrop.addFocusListener(new focusListen());
            entryPanel.add(fontTypeDrop);       
            fontColorDrop = new JComboBox(colors);
            fontColorDrop.setBounds(rjX, yRow10, dWidth, height);
            fontColorDrop.addFocusListener(new focusListen());
            entryPanel.add(fontColorDrop);
            //the eleventh row (label)
            JLabel fontSizeLabel = new JLabel("Select Font Size:");
            fontSizeLabel.setBounds(ljX, yRow11, mWidth, height);
            entryPanel.add(fontSizeLabel);
            //the final row (entry)
            fontSizeText = new JTextField("12", 2);
            fontSizeText.setBounds(ljX, yRow12, tWidth, height);
            fontSizeText.addFocusListener(new focusListen());
            entryPanel.add(fontSizeText);
            //display panel code
            //use test parameters
            //these will later be retrieved from the entries
            drawCanvas.setParams("Hello", "roundRect", Color.red,
                                100, 100, "Serif", Color.black, 12);
            //set the applet to visible
            //set to visible and display
            entire.setSize(800, 600);
            entire.setVisible(true);
        }   //end the init method
        //declare an inner class to handle events
        private class focusListen implements FocusListener
            //supply the implementation of the actionPerformed method
            //pass an event variable as the argument
            public void focusLost(FocusEvent e)
            { JOptionPane.showMessageDialog(null, "Focus lost."); } 
            //declare an empty focus gained function
            public void focusGained(FocusEvent e) {}      
        }   //end testListen class
    }   //end DemoShape class

    Sorry for glossing over your code sample, particularly as it looks like one of the best I've seen so far on the forums, but I'm pretty sure the answer you are looking for is as follows:
    Java doesn't render a component until paint() is called so until then you are not going to have any size settings because the jvm simply doesn't know how big the visual component is. This makes sense when you think about what the jvm is doing. The layout manager controls the display of the components depending on the settings it is supplied. So until it knows how many components you want, where, what kind of spacing, etc, etc, etc, how can the size be determined.
    The true cycle of events is therefore:
    create an instance of DisplayCanvas,
    add it to your container,
    make the container visible (which renders the component),
    get the size of the DisplayCanvas instance.
    You are being hampered because your desired chain of events is:
    create an instance of DisplayCanvas,
    get the size of the DisplayCanvas instance,
    add it to your container,
    make the container visible.
    This state of affairs is highly annoying and then leads to the next question "what do we do about that?". There is a cunning trick which is to get the jvm to render the component to an off-screen image, thus calculating the dimensions of the component so that you can do precisely the kind of enquiry on the object that you have been looking for. It should be noted that this may not be the visual size for all the reasons given above, but it is the "preferred size" for the component. Check the Swing tutorials and have a look at the section on Layout Managers for a run down on what that means.
    Anyway, we can use this handy code sample to determine the preferred size for your component. Notice the call to "paint()" (normally you would never make a direct call to paint() in swing) and the "g.dispose()" to free resources:
    package com.coda.swing.desktool.gui;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    public class PaintUtil
         public PaintUtil()
              super();
         public static Component paintBuffer(Component comp)
              Dimension size = comp.getPreferredSize();
              comp.setSize(size);
              BufferedImage img = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2 = img.createGraphics();
              comp.paint(g2);
              g2.dispose();
              return comp;
    }Before you make a call to getWidth() or getHeight() put in a call to "PaintUtil.paintBuffer(this);" and see what happens.
    By the way, I can't claim credit for this code ... and I really wish I could remember where I got it from myself so I can thank them :)

  • Image Fade! - doesnt want to fade!

    Hi all,
    Hope someone can help me.
    I have found a piece of code from Codelifter.com (
    http://www.codelifter.com/main/javas...lideshow2.html)
    enabling me to have a images fading on top of each other in a
    slideshow effect. However, somewhere down the line when placing in
    the code, i have obviously gone wrong because the first picture
    fades out but the others then do not fade in.
    Does this part of the code below look wrong to anyone or does
    anyone know why it may not be working!
    <body
    onload="runSlideShow();MM_preloadImages('../images/mainButtons/homeOver.jpg','../images/m ainButtons/gowerOver.jpg','../images/mainButtons/mumblesOver.jpg','../images/mainButtons/m arinaOver.jpg','../images/mainButtons/moreOver2_15.jpg','../images/find
    buttons/findHomeOver_02.gif','../images/find
    buttons/findHome_03.gif','../images/find
    buttons/findHomeOver_03.gif','../images/find
    buttons/findHome_02.gif')">
    <script
    language="JavaScript1.2">mmLoadMenus();</script>
    Thanks Nikki

    Yes thats done the trick, code as follows:
    private static Image resize2D(Image srcImage, int size)
            int w = srcImage.getWidth(null);
            int h = srcImage.getHeight(null);
            // Determine the scaling required to get desired result.
            float scaleW = (float)size / (float)w;
            float scaleH = (float)size / (float)h;
            System.out.println("Image Resizing to size:"+size+"w:"+w +":h:"+h+"scaleW:"+scaleW+"scaleH"+scaleH);
            // Create an image buffer in which to paint on.
            BufferedImage bi = new BufferedImage(size,size,BufferedImage.TYPE_INT_ARGB);
            // Set the scale.
            AffineTransform tx = new AffineTransform();
            tx.scale(scaleW, scaleH);
            // Paint image.
            Graphics2D g2d = bi.createGraphics();
            g2d.drawImage(srcImage, tx, null);
            g2d.dispose();
            return bi;
    BufferedImage newImage = resize2D(origImage, 200);
    origImage.flush();
    origImage=null;

  • Converting JPanels as image objects

    hi,
    i am having problem in converting a JPanel object which consits of some
    JLabels and images into a Image Object. Actually i want to save the JPanel as
    a jpg file which i will do with jped encoder.
    so please help me in converting this JPanel to image object

    assuming the panel is showing.... (if not, you might need to user getPreferredSize() and setVisible before paint()).
    Dimension size = panel.getSize();
    BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();
    comp.paint(g2d);

  • Export JComponent content to an image

    Hello,
    I need to export a swing component graphical representation to a JPG or GIF image.
    Somebody know how?
    Best regards,
    H?ctor

    I do.
    Oh you want me to tell you.
    There's 2 ways to get the image:
    1) Find the screen location of the component and use java.awt.Robot to get a screen capture.
    2) Create a new BufferedImage the size of the component and call paintAll() on the component, passing it the BufferedImage's Graphics object.
    Fortunately for you, I have the code for both just laying around... The advantage to using the Robot class, however, it's usually the only consistent way to get a shot of a frame which includes the window titlebar.
         public static BufferedImage grab(Component comp) {
              Point location = comp.getLocation();
              SwingUtilities.convertPointToScreen(location, comp);
              return grabImpl(comp, new Rectangle(location, comp.getSize()));
         private static BufferedImage grabImpl(Component comp, Rectangle bounds) {
              BufferedImage bi = null;
              // try using java.awt.Robot first, as this will allow it to get the
              // frame border (titlebar, etc.) for frames or dialogs.  The only
              // downside is that this grabs the window from the OS, so if there's
              // any overlapping windows or dialogs (from any application), that
              // will be included. 
              try {
                   if(robot == null) {
                        robot = new Robot();
                   bi = robot.createScreenCapture(bounds);
              } catch(java.awt.AWTException awte) {
                   bi = grabByPaint(comp);
              return bi;
         public static BufferedImage grabByPaint(Component comp) {
              Dimension size = comp.getSize();
              BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2d = bi.createGraphics();
              comp.paintAll(g2d);
              g2d.dispose();
              return bi;
         }As for saving that image, the javax.imageio package is where you want to look.

  • Extraction Key Frames from a video

    Hi all,
    I would like to know what is the best way to extract keyframe from a video.
    My Status (butr I can cahnge it)
    I'm Marco and I'm using JMF; I need for an help because I don't know how to extract keyframes from AVI and MPG files.
    I'm using the code posted in this forum for extracting all frame in a video with the adding of an if expression that in the accessFrame method that I report below:
    void accessFrame(Buffer frame) {
    BufferToImage stopBuffer = new BufferToImage((VideoFormat) frame.getFormat());
    Image stopImage = stopBuffer.createImage(frame);
    try {
    BufferedImage outImage = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
    Graphics og = outImage.getGraphics();
    og.drawImage(stopImage, 0, 0, size.width, size.height, null);
    Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
    ImageWriter writer = (ImageWriter) writers.next();
    File f = new File(frame.getSequenceNumber() + ".jpg");
    if ((frame.getFlags() & Buffer.FLAG_KEY_FRAME) != 0){{color}
    {color:#ff9900}
    ImageOutputStream ios = ImageIO.createImageOutputStream(f);
    writer.setOutput(ios);
    {color:#ff9900}
    writer.write(outImage);
    ios.close();}
    } catch (IOException e) {{color}
    System.out.println("Error :" + e);
    So, I'm able to extract some keyframe, but i'm not sure it is the correct way and my dubt grows out of the fact that without the if expression highlighted in red, it seems that I have more keyframes (those ones with flag ==1040). Another problem is that it works only with AVI because MPG instead of 1040, they have alternate sequence of 32 and 1056.
    Cheers and thank u
    Marco

    >
    With the code yoodleyee posted, frames can be extracted and converted from the raw decoded format into images, but no guarantee that the frame extracted is a key frame, isnt it?Actually, there is such a guarantee...because the FrameGrabbingControl isn't implemented in any video format that uses keyframes. So, if it works, then every frame of the video is a keyframe, and it won't work otherwise.
    How can key frames be detected with JMF and then extracted with the code provided? Any tutorial or sample code about that?They can't be. You can write a custom codec that will give you access to every frame, regardless of the format, if you're wanting to get all of the frames.
    Example: [http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/solutions/FrameAccess.html]
    But JMF doesn't have any way of dealing with key frames directly, at least that I am aware of.

  • Saving multiples objects into a file

    I want to create a single file that has multiples things inside, like pictures (png) and texts. Does someone knows how it will be the structure of the binary file?
    I'm programming a draw software like photoshop, where my layers are BufferedImages. Theses bufferedImages must be saved into a file to re-open later and edit.
    Please I want just ideas....
    thanks

    If the objects that you store in your file are fairly independent of each other, one thing that comes
    to mind is to make your file a zip file of component files. That way you can use standard tools to examine
    it and edit it if you wish.
    Another thing to note is that if your file is largely a series of images, some image file formats,
    like tiff , jpeg and gif allow you to store sequences of images in one file.
    Here's a demo that creates a tiff file holding four images, then reads the file and displays the images.
    Stardard software like Kodak's "Imaging Preview" will allow you to flip through the images in the file.
    By the way, if you don't have readers/writers for format tiff, you can get them here.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import javax.swing.*;
    public class IOExample {
        public static void main(String[] args) throws IOException {
            String urlPrefix = "http://www3.us.porsche.com/english/usa/carreragt/modelinformation/experience/desktop/bilder/icon";
            String urlSuffix = "_800x600.jpg";
            int SIZE = 4;
            BufferedImage[] images = new BufferedImage[SIZE];
            for(int i=1; i<=SIZE; ++i)
                images[i-1] = ImageIO.read(new URL(urlPrefix + i + urlSuffix));
            File file = new File("test.tiff");
            file.delete();
            int count = writeImages(images, file);
            if (count < SIZE)
                throw new IOException("Only " + count + " images written");
            images = null;
            images = readImages(file);
            if (images.length < SIZE)
                throw new IOException("Only " + images.length + " images read");
            display(images);
        public static void display(BufferedImage[] images) {
            JFrame f = new JFrame("IOExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel p = new JPanel(new GridLayout(0,1));
            for(int j=0; j<images.length; ++j) {
                JLabel label = new JLabel(new ImageIcon(images[j]));
                label.setBorder(BorderFactory.createEtchedBorder());
                p.add(label);
            f.getContentPane().add(new JScrollPane(p));
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        //suffix is "jpeg", "gif", "png", etc... according to your service providers
        public static ImageWriter getWriter(String suffix) throws IOException {
            Iterator writers = ImageIO.getImageWritersBySuffix(suffix);
            if (!writers.hasNext())
                throw new IOException("no writers for suffix " + suffix);
            return (ImageWriter) writers.next();
        public static ImageReader getReader(String suffix) throws IOException {
            Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
            if (!readers.hasNext())
                throw new IOException("no reader for suffix " + suffix);
            return (ImageReader) readers.next();
        public static int writeImages(BufferedImage[] sources, File destination) throws IOException {
            if (sources.length == 0) {
                System.out.println("Sources is empty!");
                return 0;
            } else {
                ImageWriter writer = getWriter(getSuffix(destination));
                ImageOutputStream out = ImageIO.createImageOutputStream(destination);
                writer.setOutput(out);
                writer.prepareWriteSequence(null);
                for(int i=0; i<sources.length; ++i)
                    writer.writeToSequence(new IIOImage(sources, null, null), null);
    writer.endWriteSequence();
    return sources.length;
    public static BufferedImage[] readImages(File source) throws IOException {
    ImageReader reader = getReader(getSuffix(source));
    ImageInputStream in = ImageIO.createImageInputStream(source);
    reader.setInput(in);
    ArrayList images = new ArrayList();
    GraphicsConfiguration gc = getDefaultConfiguration();
    try {
    for(int j=0; true; ++j)
    images.add(toCompatibleImage(reader.read(j), gc));
    } catch(IndexOutOfBoundsException e) {
    return (BufferedImage[]) images.toArray(new BufferedImage[images.size()]);
    public static String getSuffix(File file) throws IOException {
    String filename = file.getName();
    int index = filename.lastIndexOf('.');
    if (index == -1)
    throw new IOException("No suffix given for file " + file);
    return filename.substring(1+index);
    //make compatible with gc for faster rendering
    public static BufferedImage toCompatibleImage(BufferedImage image, GraphicsConfiguration gc) {
    int w = image.getWidth(), h = image.getHeight();
    int transparency = image.getColorModel().getTransparency();
    BufferedImage result = gc.createCompatibleImage(w, h, transparency);
    Graphics2D g = result.createGraphics();
    g.drawRenderedImage(image, null);
    g.dispose();
    return result;
    public static GraphicsConfiguration getDefaultConfiguration() {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    return gd.getDefaultConfiguration();

Maybe you are looking for

  • Accounting doc typelink with billing doc type

    Hi, I want to see the configuration settings to be done for the accounting document type whenever a Invoice is posted to accounting.Basically if a standard Invoice F2 is posted to accounting then an accounting doc type RV is created.So I would like t

  • ITunes keeps creating duplicate m4p files for existing m4a files

    I noticed in 10.0 that I had duplicates of many of my purchased music, an m4a and an m4p. I tried removing the m4p files through iTunes, and through Finder. I have used the Display Exact Duplicate to identify some of them and then removed them. But a

  • Creating a drop down list using acrobat forms

    I'm working on a macintosh computer, sysem 10, acrobat 9. I'm a financial printer and I'm making a prepress order form in a pdf file I want to make a drop down list so that I can change print venders. The information in the drop down list will contai

  • How to run TCK using Java Card Sun reference model from eclipse

    Hi all, can any one help me by giving an idea about running java card TCK using sun reference model from eclipse IDE. Thanks Murali

  • Color of Backgground in i tunes Library

    For some reason the color of my i tunes library has a purple background. It is harder to read than the default way. Is trhere a way I can change the background?