0

我有一个 Java 小程序(在 NetBeans 7.4 中开发并使用 JMF)用于从网络摄像头拍照,它在启动时自动初始化网络摄像头(通过使用 JMF)...

(小程序)

在此处输入图像描述

为了使其运行,需要在 JAR 文件的同一目录中添加 jmf.properties 文件,如下所示:

在此处输入图像描述

我尝试在 HTML 页面中显示此组件以从 WebBrowser 获取快照,但 JMF 在那里不起作用,每次运行它时都会收到此消息(尝试使用 JMF 初始化网络摄像头):

在此处输入图像描述

然后它只显示小程序

在此处输入图像描述

这是我的 HTML 代码(由 Netbeans 生成)

<HTML>
<HEAD>
   <TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>

<!--
*** GENERATED applet HTML launcher - DO NOT EDIT IN 'BUILD' FOLDER ***

If you need to modify this HTML launcher file (e.g., to add applet parameters), 
copy it to where your applet class is found in the SRC folder. If you do this, 
the IDE will use it when you run or debug the applet.

Tip: To exclude an HTML launcher from the JAR file, use exclusion filters in 
the Packaging page in the Project Properties dialog.

For more information see the online help.
-->

<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>

<P>
<APPLET codebase="classes" code="com/xxx/pantallas/CamaraApplet.class" width=350 height=200></APPLET>
</P>

<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>

以及我打开 HTML 的目录

在此处输入图像描述

对于使网络摄像头从 HTML 运行的任何帮助,我将不胜感激


要求:

***在项目中使用 JMF 需要库

为了使这个项目运行,我使用:

  • 2班
  • 1 个小程序(主要)
  • 1 个 HTML 文件

CameraApplet.java (小程序)

import java.lang.reflect.InvocationTargetException;
import javax.media.Player;
import javax.swing.JPanel;
import static com.sun.java.accessibility.util.AWTEventMonitor.addWindowListener;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class CameraApplet extends javax.swing.JApplet {
    private Player  p1;

    public  Player  getPlayer()             {return p1;}
    public  void    setPlayer(Player pin)   {p1 = pin;}
    public  JPanel  getCamera()             {return panelCam;}

    private void    initComponents2() {

        //Register all the listeners of the Events
        AuxClass e = new AuxClass(this);
        addWindowListener(e);
        jmCArchivo.addActionListener(e);

        //Loads in menu all detected devices
        AuxClass.DevicesMenuApplet(this, jmDispositivos);

        //applet size
        setSize(680, 840);

        //Autostarts camera
        AuxClass.setCameraApplet(CameraApplet.this,
                                 AuxClass.detectAvailableWebCameras().get(0),
                                 0);
    }

    @Override
    public void init() {
        //Establecer los valores de look and feel del applet
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } 
        catch(ClassNotFoundException | IllegalAccessException | InstantiationException | UnsupportedLookAndFeelException e){
            AuxClass.showErrorMessage(null, "Ocurrio un error: " + e.toString());
        }

        /* crea y muestra el applet */
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                    initComponents2();
                }
            });
        } 
        catch (InterruptedException | InvocationTargetException e){
            AuxClass.showErrorMessage(null, "Ocurrio un error: " + e.toString());
        }
    }

    /**
     * This method is called from within the init() method to initialize the
     * form. WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        panelCam = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jmCapturar = new javax.swing.JMenu();
        jmCArchivo = new javax.swing.JMenuItem();
        jmDispositivos = new javax.swing.JMenu();

        setPreferredSize(new java.awt.Dimension(640, 480));

        panelCam.setBorder(javax.swing.BorderFactory.createTitledBorder("Camara Web"));
        panelCam.setPreferredSize(new java.awt.Dimension(640, 480));
        panelCam.setLayout(new java.awt.BorderLayout());

        jmCapturar.setText("Capturar");

        jmCArchivo.setText("En Archivo");
        jmCapturar.add(jmCArchivo);

        jMenuBar1.add(jmCapturar);

        jmDispositivos.setText("Dispositivos");
        jMenuBar1.add(jmDispositivos);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelCam, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelCam, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>                        


    // Variables declaration - do not modify                     
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jmCArchivo;
    private javax.swing.JMenu jmCapturar;
    private javax.swing.JMenu jmDispositivos;
    private javax.swing.JPanel panelCam;
    // End of variables declaration                   
}

辅助类.java

import java.awt.Component;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.media.Buffer;
import javax.media.CannotRealizeException;
import javax.media.CaptureDeviceInfo;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.NoPlayerException;
import javax.media.Player;
import javax.media.cdm.CaptureDeviceManager;
import javax.media.control.FormatControl;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.RGBFormat;
import javax.media.format.VideoFormat;
import javax.media.format.YUVFormat;
import javax.media.util.BufferToImage;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JOptionPane;

public class AuxClass implements WindowListener,ActionListener{

    private final CameraApplet padreApplet;

    public AuxClass(CameraApplet padreApplet){this.padreApplet = padreApplet;}

    //Menu Actions
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("En Archivo")){
                AuxClass.saveImageFile(AuxClass.capturePhoto(padreApplet.getPlayer()),
                                                              AuxClass.SaveFileAsDialog(padreApplet));  
        }
    }



    @Override
    public void windowClosing(WindowEvent e) {AuxClass.stopPlayer(padreApplet.getPlayer());}
    @Override
    public void windowOpened(WindowEvent e) {
    }
    @Override
    public void windowClosed(WindowEvent e) {
    }
    @Override
    public void windowIconified(WindowEvent e) {
    }
    @Override
    public void windowDeiconified(WindowEvent e) {
    }
    @Override
    public void windowActivated(WindowEvent e) {
    }
    @Override
    public void windowDeactivated(WindowEvent e) {
    }





    //This method handles the Saving image file as. Jpg
    public static File SaveFileAsDialog(Component padre){

        JFileChooser    f;
        File            imageFile   = null;
        String          imagePath   = "";
        f                           = new JFileChooser();

        f.setDialogTitle("Save File As...");
        f.showSaveDialog(padre);

        if(f.getSelectedFile() != null){
            imagePath  = f.getSelectedFile().getAbsolutePath();

            if (imagePath.lastIndexOf(".") > 0)
                imagePath  = imagePath.substring(0,imagePath.lastIndexOf("."));

            imagePath   = imagePath + ".jpg";
            imageFile   = new File(imagePath);
        }
        return imageFile;
    }

    public static void showErrorMessage(Component padre,String mensaje){
        JOptionPane.showMessageDialog(padre,mensaje,"Captura Camara Web ",JOptionPane.ERROR_MESSAGE);
    }


    //This is the link between camera and the player class first time you turn the camera on
    public static void setCameraApplet(CameraApplet camera,String device,int format){
        Player player   = AuxClass.createPlayer(device, format);
        camera.setPlayer(player);
        AuxClass.startPlayer(player);
        camera.getCamera().add(player.getVisualComponent());
    }



    //----------------------------------------Player methods----------------------------------------
        public static void startPlayer(Player p){
        if(p!=null) p.start();
    }

    public static void stopPlayer(Player p){
        if(p!=null){
            p.stop();
            p.deallocate();
            p.close();
        }
    }

    public static Image capturePhoto(Player p){
        Image img   = null;
        if(p != null){
            FrameGrabbingControl fgc    = (FrameGrabbingControl)p.getControl("javax.media.control.FrameGrabbingControl");
            Buffer               buf    = fgc.grabFrame();
            BufferToImage        btoi   = new BufferToImage((VideoFormat)buf.getFormat());
            img                         = btoi.createImage(buf);
        }
        else{
            AuxClass.showErrorMessage(null, "¡Player has not started yet!");
        }
        return img;
    }

    public static void saveImageFile(Image img,File imagenArch){       
        String format = "JPG";
        try {
            if(img !=null && imagenArch!=null)
                ImageIO.write((RenderedImage) img, format , imagenArch);
        } 
        catch (IOException e) {
            AuxClass.showErrorMessage(null, "Disk write error: " + e.toString());
        }
    }    

    //JDevices methods
        //returns webCam's name selected
    public static CaptureDeviceInfo returnDevice(String name){
        return CaptureDeviceManager.getDevice(name);
    }

    //open webCamera selected
    public static MediaLocator openDevice(CaptureDeviceInfo cdi){
        return cdi.getLocator();
    }

    //Crea un Player a partir del nombre del dispositivo y del indice del formáto que se desea aplicar
    public static Player createPlayer(String device,int f){        
        Player p = null;

        try {
            p                           = Manager.createRealizedPlayer(openDevice(returnDevice(device)));
            Format []formats;
            formats                     = getFormats(device);
            FormatControl formatControl = (FormatControl)p.getControl("javax.media.control.FormatControl");
            formatControl.setFormat (formats[f]);
        } 
        catch (CannotRealizeException | IOException | NoPlayerException e) {
            AuxClass.showErrorMessage(null, "Input-Output Error: \n" + e.toString());
        }
        return p;
    }

    //Returns available formats, passing device's name
    public static Format[] getFormats(String name){
        CaptureDeviceInfo   cdi1        = returnDevice(name);
        Format              []formats   = cdi1.getFormats();
        return formats;
    }

    //Switches player's resolutions
    public static void changeResolution(Player p,String device,int format){
        if(p != null) p.stop();

        Format []formats            = getFormats(device);
        FormatControl formatControl = (FormatControl)p.getControl("javax.media.control.FormatControl");
        formatControl.setFormat (formats[format]);
        p.start();
    }

    //Loads all the cameras detected and its actions within a JMenu object 
    public static void DevicesMenuApplet(CameraApplet camera, JMenu devices){

        List<String> cameraList = detectAvailableWebCameras();
        Format[] formatsArray;

        for(int j= 0; j< cameraList.size(); j++){
            JMenu               menuFormato     = new JMenu(cameraList.get(j));
            JMenuFormato        cameraRes       = null;
            CaptureDeviceInfo dev               = CaptureDeviceManager.getDevice(cameraList.get(j));
            formatsArray                        = dev.getFormats();

              //get the formats/resolutions availables:
              for(int i = 0; i < formatsArray.length; i++){

                  if(formatsArray[i].getEncoding().compareTo("yuv") == 0){
                      //this returns a menu element with label of the resolution and its actionlistener
                      cameraRes = new JMenuFormato(cameraList.get(j), 
                                                  formatsArray[i].getEncoding()+" "+
                                                 ((YUVFormat)formatsArray[i]).getSize().width + "x" +
                                                 ((YUVFormat)formatsArray[i]).getSize().height, 
                                                  i,
                                                 ((YUVFormat)formatsArray[i]).getSize().width ,
                                                 ((YUVFormat)formatsArray[i]).getSize().height ,
                                                  camera,
                                                  camera.getCamera());
                  }
                  else 
                  if(formatsArray[i].getEncoding().compareTo("rgb") == 0){
                      cameraRes = new JMenuFormato(cameraList.get(j),
                                                  formatsArray[i].getEncoding()+" "+
                                                  ((RGBFormat)formatsArray[i]).getSize().width+"x"+
                                                  ((RGBFormat)formatsArray[i]).getSize().height,
                                                  i,
                                                  ((RGBFormat)formatsArray[i]).getSize().width,
                                                  ((RGBFormat)formatsArray[i]).getSize().height,
                                                   camera,
                                                   camera.getCamera());
                  }
                  menuFormato.add(cameraRes);//Adds the menu to JMenu list
              }
              devices.add(menuFormato);     
            }     
    }

    //Detects all the camera devices detected inside a List
    public static List<String> detectAvailableWebCameras(){
        //make a reference to a JMF function for obtaining the devices
        List<String> deviceList = CaptureDeviceManager.getDeviceList(null); 
        List<String> cameraList = new ArrayList<>();
        Iterator it             = deviceList.iterator();         
        String name             = "";                            //Stores all the names of the devices
        while (it.hasNext()){                                    //Makes a cycle for listing all stored devices
          CaptureDeviceInfo cdi = (CaptureDeviceInfo)it.next();  //Get device info
          name                  =  cdi.getName();                //Get detected device's name

          //Filter only camera devices
          if(name.indexOf("Image") != -1){cameraList.add(name);}
      }
    return cameraList;
    }

}

JMenuFormato.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

//this class implements logic for obtaining menus and resolutions JFrame
public class JMenuFormato extends JMenuItem implements ActionListener{

    private final int           width;
    private final int           high;
    private final int           ordinal;

    private final JPanel        modifiable;
    private final String        device;

    private final CameraApplet  cameraApplet;

    //Constructores (Version Applet y version JFrame)
     public JMenuFormato(String device,String label,int ordinal,int width,int high,CameraApplet cameraApplet,JPanel modifiable){

        super(label);

        this.modifiable     = modifiable;
        this.width          = width;
        this.high           = high;
        this.cameraApplet   = cameraApplet;
        this.device         = device;
        this.ordinal        = ordinal;
        this.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //Acciones para Applet (Class)
            if(cameraApplet.getPlayer() == null){
                AuxClass.setCameraApplet(cameraApplet, device, ordinal);
            }
            else{
                AuxClass.changeResolution(cameraApplet.getPlayer(),device, ordinal);
            }   
        cameraApplet.setSize(width+200, high+200); 
    }
}

索引.html

<html>
    <head>
        <title>WebCam app</title>
    </head>
    <body>
        <div><applet code="CameraApplet.class" archive="CapturaCamaraWeb.jar" width="680" height="840"></applet></div>
    </body>
</html>
4

0 回答 0