How to use the frameaccess code to convert video frames to jpeg files

Hello everyone. I am working on a project on video processing, and i need to be able to do image processing on individual video frames. However, to do this, I need to convert the frames to an appropriate format, namely jpeg. It is actually the conversion from buffer frame to BufferedImage that is important, as i already have an approximate knowledge of filewriter for the saving of already rendered file.
The original frameaccess code can be found here: http://java.sun.com/products/java-media/jmf/2.1.1/solutions/FrameAccess.html
there are several other threads tied to this topic, some of which do not work for me, or simply do not suit my needs, so please do not link me to them unless you are sure its the real solution.
if any one could help me by showing me the way of doing it correctly, and maybe give a nice short explanation, i would be very grateful.
Thanks you.
P.s: i am only a beginner to intermediate student in java and programming in general so...

Here is the code i am currently using.
package Test;
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.media.*;
import javax.media.control.TrackControl;
import javax.media.Format;
import javax.media.format.*;
import javax.media.bean.playerbean.MediaPlayer;
import javax.media.util.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.awt.image.*;
import javax.imageio.ImageWriter;
import javax.imageio.ImageIO;
import javax.media.control.FrameGrabbingControl;
* 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 extends Frame implements ControllerListener {
Processor p;
Object waitSync = new Object();
boolean stateTransitionOK = true;
* 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(p.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];
          break;
     if (videoTrack == null) {
     System.err.println("The input media does not contain a video track.");
     return false;
     System.err.println("Video format: " + videoTrack.getFormat());
     // Instantiate and set the frame access codec to the data flow path.
     try {
     Codec codec[] = { new PreAccessCodec(),
                    new PostAccessCodec()};
     videoTrack.setCodecChain(codec);
     } catch (UnsupportedPlugInException e) {
     System.err.println("The process does not support effects.");
     // Realize the processor.
     p.prefetch();
     if (!waitForState(p.Prefetched)) {
     System.err.println("Failed to realize the processor.");
     return false;
     // Display the visual & control component if there's one.
     setLayout(new BorderLayout());
     Component cc;
     Component vc;
     if ((vc = p.getVisualComponent()) != null) {
     add("Center", vc);
     if ((cc = p.getControlPanelComponent()) != null) {
     add("South", cc);
     // Start the processor.
     p.start();
     setVisible(true);
     return true;
public void addNotify() {
     super.addNotify();
     pack();
* 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) throws IOException {
     /*if (args.length == 0) {
     prUsage();
     System.exit(0);
     //String url = args[0];
     String url = new String ("file:D:FiMs/avpr.avi");
     if (url.indexOf(":") < 0) {
     prUsage();
     System.exit(0);
     MediaLocator ml;
     //MediaPlayer mp1 = new javax.media.bean.playerbean.MediaPlayer();
     //mp1.setMediaLocation(new java.lang.String("file:D:/FiMs/299_01_hi.mpg"));
     //mp1.start();
     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";
     // No op.
public void open() {
     // No op.
     public void close() {
     // No op.
     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.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() {
     supportedIns = new Format [] {
          new RGBFormat()
* 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("Post: frame #: " + frame.getSequenceNumber() +
               ", time: " + ((float)t)/100f +
               ", len: " + frame.getLength());
     public String getName() {
     return "Post-Access Codec";
and here is what itprabhu5 proposed to use to convert and save the frames as .png(or .jpeg in the same way)
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.media.*;
import javax.media.control.*;
import javax.media.format.*;
import javax.media.util.*;
* Grabs a frame from a Webcam, overlays the current date and time, and saves the frame as a PNG to c:\webcam.png
* @author David
* @version 1.0, 16/01/2004
public class FrameGrab
     public static void main(String[] args) throws Exception
          // Create capture device
          CaptureDeviceInfo deviceInfo = CaptureDeviceManager.getDevice("vfw:Microsoft WDM Image Capture (Win32):0");
          Player player = Manager.createRealizedPlayer(deviceInfo.getLocator());
          player.start();
          // Wait a few seconds for camera to initialise (otherwise img==null)
          Thread.sleep(2500);
          // Grab a frame from the capture device
          FrameGrabbingControl frameGrabber = (FrameGrabbingControl)player.getControl("javax.media.control.FrameGrabbingControl");
          Buffer buf = frameGrabber.grabFrame();
          // Convert frame to an buffered image so it can be processed and saved
          Image img = (new BufferToImage((VideoFormat)buf.getFormat()).createImage(buf));
          BufferedImage buffImg = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
          Graphics2D g = buffImg.createGraphics();          
          g.drawImage(img, null, null);
          // Overlay curent time on image
          g.setColor(Color.RED);
          g.setFont(new Font("Verdana", Font.BOLD, 16));
          g.drawString((new Date()).toString(), 10, 25);
          // Save image to disk as PNG
          ImageIO.write(buffImg, "png", new File("c:\\webcam.png"));
          // Stop using webcam
          player.close();
          player.deallocate();
          System.exit(0);                    
however, i am unable to use it together with my code... i m not even sure if im using it at the right place.. (note that u will have to discard some lines from the second code, because it is actually grabbing frames from a webcam in that example)
if any1 can make it happen please help me. thx.

Similar Messages

  • How to use the t-code vf31 tor taking print out of invoice

    Hi,
      How to use the t-code vf31 for taking print out,am getting an error like no message for initial processing exist,
    venu

    Hi,
    Please find the steps
    Output type                     RD00
    Transmission medium             1
    Sort order                      01
    Processing mode                 1
    Please give the oppropriate fields,
    if the still error persists  check the configuration in NACE transaction code.
    thanks
    Kuntla

  • How to get the source code of an HTML page in Text file Through J2EE

    How to get the source code of an HTML page in Text file Through J2EE?

    Huh? If you want something like your browser's "view source" command, simply use a URLConnection and read in the data from the URL in question. If the HTML page is instead locally on your machine, use a FileInputStream. There's no magic invovled either way.
    - Saish

  • How to get the source code of an HTML page in Text file Through java?

    How to get the source code of an HTML page in Text file Through java?
    I am coding an application.one module of that application is given below:
    The first part of the application is to connect our application to the existing HTML form.
    This module would make a connection with the HTML page. The HTML page contains the coding for the Form with various elements. The form may be a simple form with one or two fields or a complex one like the form for registering for a new Bank Account or new email account.
    The module will first connect through the HTML page and will fetch the HTML code into a Text File so that the code can be further processed.
    Could any body provide coding hint for that

    You're welcome. How about awarding them duke stars?
    edit: cheers!

  • Afther repeatedly wrong pass code (iPhone 4) How to use the correct code now?

    Others used repeatedly the wrong pass code on my iPhone 4. I do have the correct code and don't want to loose my content. How to handle now?

    If you no longer are permitted to enter the right passcode, then it's too late to save anything:
    Locked Out, Forgot Lock or Restrictions Passcode, or Need to Restore Your Device: Several Alternative Solutions
    A
    1. iOS- Forgotten passcode or device disabled after entering wrong passcode
    2. iPhone, iPad, iPod touch: Wrong passcode results in red disabled screen
    3. Restoring iPod touch after forgotten passcode
    4. What to Do If You've Forgotten Your iPhone's Passcode
    5. iOS- Understanding passcodes
    6. iTunes 10 for Mac- Update and restore software on iPod, iPhone, or iPad
    7. iOS - Unable to update or restore
    Forgotten Restrictions Passcode Help
                iPad,iPod,iPod Touch Recovery Mode
    You will need to restore your device as New to remove a Restrictions passcode. Go through the normal process to restore your device, but when you see the options to restore as New or from a backup, be sure to choose New.
    You can restore from a backup if you have one from BEFORE you set the restrictions passcode.
    Also, see iTunes- Restoring iOS software.

  • How To Use The Pen Tool in Adobe Illustrator, Photoshop and InDesign CS6 | Creative Suite Podcast: Designers | Adobe TV

    In this episode of the Adobe Creative Suite Podcast Terry White shows how to use the Pen Tool to create Art, Frames and to trace images in Photoshop CS6. If you've never used the Pen Tool before, this is your video!
    http://adobe.ly/STegFg

    With the pen tool in Indesign, is there a way of making the points not join if you want to make a few single lines?

  • How to Use the JAVA SCRIPT code in .htm page of the component

    Hi .
    In my requirement i have to use Java Script Function in .htm code ..how to use the java script code and functions in .htm???
    thank you
    B.Mani

    Check this document  [Arun's Blog|http://wiki.sdn.sap.com/wiki/display/CRM/CRMWebClientUI-TalkingwithJava+Script]
    Regards
    Kavindra

  • How can i use the project code instead of project xml?

    hello
    i use the sessionbean+toplink structure,after i finish the o-r mapping by using the mapping work bench,i generate the project xml file,then in the "session.xml" file,i refer to the project xml,then i can use it from sessionbean.
    i hear that if i use the project code instead of project xml file,it will be more performant,is that true?
    otherwise,how can i use the project code instead of project xml file?i mean, in "session.xml", i can use the "<project-xml>" tag to refer to the project xml file,then in my session bean,i get the server session by read the "session.xml" file.but if i use the project code,how can i refer it from the "session.xml"?the examples that come with the toplink installation only tell me how can i use the project xml file within the session bean,it don't give me any clue about using the project code in the sesion bean,who can give me a step-by-step instruction and code snippet?
    thank you very much?

    There is a slight performance gain during session load at startup but there is no difference at runtime. The choice of which to use is dependent upon you build process. Whether it is easier to submit a new version of the class into the comile build process vs an XML file. In most cases it is just a preference of the development team.
    When you use the project-class you'll need to generate the source code and compile it into your system. Typically it is packaged with the persistent classes. You may need to configure your environment so that the class-loaders have access to these classes (same for the XML case).
    When using the project-class you simply replace the project-xml entry like this:
    <project-class>oracle.toplink.demos.employee.relational.EmployeeProject</project-class>
    The DTD for the session.xml file is found at <TOPLINK_HOME>\core\sessions_4_5.dtd. It is also in the documentation at:
    http://otn.oracle.com/docs/products/ias/doc_library/90200doc_otn/toplink.903/b10064/a-sessio.htm#634246
    Doug Clarke
    Product Manager
    Oracle9iAS TopLink

  • How do I do use the custom code and format for a percentage with 2 decimals in Report Builder 3.0?

    In Report Builder 3.0, I have the following custom code entered:
      Public Function SafeDivide(Numerator as String, Denominator as String) as String
    Try
    If Numerator = “” or Denominator = “” then
    Return “-“
    End if
    If Numerator = “-“ or Denominator = “-“ then
    Return “-“
    End If
    If CDbl(Numerator) =0 or CDbl(Denominator) = 0 then
    Return “-“
    End if
    If IsNothing(Numerator) or IsNothing(Denominator) then
    Return "-"
    End if
    Return Val( ( (CDbl(Numerator) / CDbl(Denominator) )*100 ) )
    Catch
    Return "-"
    End Try
    End Function
    I call the custom code in the cell with the following equation:
      =Code.SafeDivide(sum(Fields!TY_UNITS.Value)-sum(Fields!LY_UNITS.Value),sum(Fields!LY_UNITS.Value))
    I have the format for the cell set to 0.00%, but it’s not being followed.
    I want the result to be formatted as a Percentage, but instead I get values like: 
    -78.9473684210
    80
    300
    -100
    I have the format for the cell set to 0.00%, but it’s not being followed.
    How do I do use the custom code and format for a percentage with 2 decimals?

    Hi AngP,
    After testing the issue in my local environment, I can reproduce it. Based on my research, I find this issue is caused by the type of Units_VAR_Percentage cell is string, while the type of CDbl(Parameters!Var_Threshold.Value) is double, so they cannot be
    compared.
    To fix this issue, we can add a hidden column (Textbox91) next to the Units_VAR_Percentage column, and type =(sum(Fields!TY_UNITS.Value)-sum(Fields!LY_UNITS.Value)) /sum(Fields!LY_UNITS.Value) as the expression. Then use the expression below to control the
    BackgroundColor:
    =iif(iif(reportitems!Units_VAR_Percentage.Value=CStr(format(reportitems!Textbox91.Value,"0.00%")),reportitems!Textbox91.Value,0)>CDbl(Parameters!Var_Threshold.Value),"Yellow","PaleTurquoise")
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • I don't know how to use the canlendars function and the notes are kind of messy code,anyone help me

    i don't know how to use the canlendars function and the notes are kind of messy code,anyone help me

    Step by step:
    1. On your main vi Front Panel, create your boolean indicator.
    2. On the block diagram, right click the new boolean indicator and select Create - Reference.
    3. On sub-vi front panel, create boolean indicator (or use one that is already created).
    4. On sub-vi front panel, create a reference (Controls Palette - Refnum - Control Refnum).
    5. Right click on the newly created Refnum and select Select Vi Server Class - Generic - GObject - Control - Boolean. The refnum label changes to BoolRefnum.
    6. On sub-vi block diagram, create Property Node (Functions - Application Control - Property Node). Find the BoolRefnum and move it close to the new Property Node.
    7. Wire the BoolRefnum to the reference input of the property node.
    8.
    Right click on the property node and select Change to All Write.
    9. Move mouse to point to Visible inside property node box, left click and select Value.
    10. Wire the boolean indicator from step 3 to the Value input of the property node.
    11. On sub-vi front panel, right click on icon and select Show Connector.
    12. Click on empty connector spot then click on the new BoolRefnum. Save your sub-vi.
    13. On main vi block diagram, connect refernece created in step 2 to the new connector terminal of sub-vi.
    14. Save and run.
    Here are the modified vi's.
    - tbob
    Inventor of the WORM Global
    Attachments:
    Pass_a_Reference.vi ‏20 KB
    GL_Flicker_mod.vi ‏83 KB

  • How to create an Invoice for the sales order using the T-Code VF01

    Hello Experts,
    How to create an Invoice for a sales order using the T-Code VF01?
    Thanks in advace,
    Suma

    hi,
    Make the following settings-
    1. Create sales document and billing type
    2. assign billing type in sales document type config VOV8
    3. Activate itemcategory as sales order related billing
    4. Maintain copy control header and item level between sales order and billing
    5. Maintain pricing procedure for sales order and billing
    6. Define Output procedure in case to print invoice
    Regards
    Goutham

  • How to restrict a user from using the transaction code SU01?

    How can I grant a profile to a user with the profile SAP_ALL except running the transaction code SU01?
    I know how to lock the transaction code using SM01 but is there any other way to do it.

    Go to S_TCODE
    Double click on it and give the combinations like        A*  -   X*
                                                                                 SU00
                                                                                 SU02 - Z*
                         Try this one definately it will work.

  • How to disable the security code and use only the Touch ID

    how to disable the security code and use only the Touch ID

    You can't use Touch ID without a passcode.
    http://support.apple.com/kb/HT5883

  • How to use the LAN NetStream for peer transmission, please help, write a sample code

    How to use the LAN NetStream for peer transmission, please help, write a sample code

    No reply, I reply, Oh

  • HT2737 how do you use the download code if the redemption code is unlegible from being scratched out to much

    I scratched out my itunes gift card way to much and now i can't read the redemption code, is there anything i can do to still use the gift card. maybe using the download code instead?
    please respond back
    -emily

    With any luck, the following document may be of some assistance with that:
    iTunes Store: Invalid, inactive, or illegible codes

Maybe you are looking for

  • HT5312 How do I use my rescue email to reset my security questions?

    Ever since I got a new phone in December I haven't been able to make purchases on the App Store (free stuff I can get of course). Whenever I go to buy something it asks for the answers to my security questions. And for some reason all the answers I c

  • Adobe PDF Printer uninstalls

    Hi, I have Adobe Creative Suite - every couple of days the Adobe PDF printer uninstalls & is no longer available to use. This means I have to go X Pro and select Help > Repair Acrobat Installation every couple of days, a process which takes about 20

  • SAP business connector 4.8

    Hi Experts, Request you to please suggest me. i am new to SAP BC. my team given me work to migrate SAP business connector 4.8 one location to new location. So request you to please suggest me how i can achieve this task. Thanks, Navneet Kumar

  • I need to re-download an older music purchase.

    I need to re-download an older music purchase. Itunes store indicates it has been purchased but it does not appear in my itunes library.  I purchased the song 11/2011.  No change of Itunes ID and running all of the latest software on PC and phone.  I

  • Moved from DC to NC now smtp authentication with Cox won't work on roadrunn

    I just moved from DC to NC. I have a cox.net email I prefer to use. Cox allows smtp authentication over other ISPs. I had RCN in DC and it worked perfectly. But now, with Time Warner (RoadRunner), it doesn't work. (Incoming still works fine, this is