在黑莓中拍照

时间:2012-04-19 02:17:37

标签: blackberry camera blackberry-simulator

我是黑莓新手。创建一个程序从黑莓相机拍照时我遇到了麻烦。我使用了Blackberry开发者网站Code sample: Taking a picture in a BlackBerry device application提供的示例代码。 构建此代码时我没有遇到任何问题,但是它不能在模拟器或黑莓手机上运行。 这是我正在使用的代码。请帮我!谢谢你!

package mypackage;

import net.rim.device.api.amms.control.camera.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;

public class ImageCaptureDemo extends UiApplication {
    public static void main(String[] args) {
        ImageCaptureDemo app = new ImageCaptureDemo();
        app.enterEventDispatcher();
    }

    public ImageCaptureDemo() {
        pushScreen(new ImageCaptureDemoScreen());
    }

    class ImageCaptureDemoScreen extends MainScreen {
        Player _p;
        VideoControl _videoControl;

        public ImageCaptureDemoScreen() {
            try {
                _p = javax.microedition.media.Manager
                        .createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
                _p.realize();
                _videoControl = (VideoControl) _p.getControl("VideoControl");

                if (_videoControl != null) {
                    Field videoField = (Field) _videoControl.initDisplayMode(
                            VideoControl.USE_GUI_PRIMITIVE,
                            "net.rim.device.api.ui.Field");
                    _videoControl.setDisplayFullScreen(true);
                    _videoControl.setVisible(true);
                    _p.start();

                    EnhancedFocusControl efc = (EnhancedFocusControl) _p
                            .getControl("net.rim.device.api.amms.control.camera.EnhancedFocusControl");
                    efc.startAutoFocus();

                    if (videoField != null) {
                        add(videoField);
                    }
                }
            } catch (Exception e) {
                Dialog.alert(e.toString());
            }
        }

        protected boolean invokeAction(int action) {
            boolean handled = super.invokeAction(action);

            if (!handled) {
                if (action == ACTION_INVOKE) {
                    try {
                        byte[] rawImage = _videoControl.getSnapshot(null);
                    } catch (Exception e) {
                        Dialog.alert(e.toString());
                    }
                }
            }
            return handled;
        }
    }
}

1 个答案:

答案 0 :(得分:4)

public  class CameraScreen extends MainScreen
{
    private VideoControl _videoControl;
    private Field _videoField;
    private EncodingProperties[] _encodings;    
    private int _indexOfEncoding = 0;
    private ZoomControl _zoomControl;
    CameraScreen cameraScreen;
    public CameraScreen()
    {
        cameraScreen= this;
        initializeCamera();
        initializeEncodingList();
        if(_videoField != null)
        {
            createUI();
        }
        else
        {
            add( new RichTextField( "Error connecting to camera." ) );
        }
    }
    protected boolean touchEvent(TouchEvent event)
    {
        if(event.getEvent() == TouchEvent.GESTURE)
        {
            TouchGesture gesture = event.getGesture();
            if(gesture.getEvent() == TouchGesture.SWIPE)
            {
                final int direction = gesture.getSwipeDirection();
                UiApplication.getApplication().invokeLater(new Runnable()
                {
                    public void run()
                    {
                        if(direction == TouchGesture.SWIPE_NORTH)
                        {
                            _zoomControl.setDigitalZoom(ZoomControl.NEXT);
                        }
                        else if(direction == TouchGesture.SWIPE_SOUTH)
                        {
                            _zoomControl.setDigitalZoom(ZoomControl.PREVIOUS);
                        }
                    }
                });

                return true;
            }
        }

        return false;
    }

    public void takePicture()
    {
        try
        {
            String encoding = null;            

            if( _encodings != null )
            {
                encoding = _encodings[_indexOfEncoding].getFullEncoding();
            }
            createImageScreen( _videoControl.getSnapshot( encoding ) );
        }
        catch(Exception e)
        {
        }  
    }

    protected boolean onSavePrompt()
    {
        return true;
    }

    /**
     * Initializes the Player, VideoControl and VideoField
     */
    private void initializeCamera()
    {
        try
        {
            Player player = Manager.createPlayer( "capture://video" );
            player.realize();
            _videoControl = (VideoControl)player.getControl( "VideoControl" );

            if (_videoControl != null)
            {
                _videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
                _videoControl.setDisplayFullScreen(true);
                _videoControl.setVisible(true);
            }

            player.start();
        }
        catch(Exception e)
        {
        }
    }

    /**
     * Initialize the list of encodings
     */
    private void initializeEncodingList()
    {
        try
        {
            String encodingString = System.getProperty("video.snapshot.encodings");
            String[] properties = StringUtilities.stringToKeywords(encodingString);
            Vector encodingList = new Vector();
            String encoding = "encoding";
            String width = "width";
            String height = "height";
            EncodingProperties temp = null;

            for(int i = 0; i < properties.length ; ++i)
            {
                if( properties[i].equals(encoding))
                {
                    if(temp != null && temp.isComplete())
                    {
                        // Add a new encoding to the list if it has been
                        // properly set.
                        encodingList.addElement( temp );
                    }
                    temp = new EncodingProperties();

                    // Set the new encoding's format
                    ++i;
                    temp.setFormat(properties[i]);
                }
                else if( properties[i].equals(width))
                {
                    // Set the new encoding's width
                    ++i;
                    temp.setWidth(properties[i]);
                }
                else if( properties[i].equals(height))
                {
                    // Set the new encoding's height
                    ++i;
                    temp.setHeight(properties[i]);
                }

            }

            // If there is a leftover complete encoding, add it.
            if(temp != null && temp.isComplete())
            {
                encodingList.addElement( temp );
            }

            // Convert the Vector to an array for later use
            _encodings = new EncodingProperties[ encodingList.size() ];
            encodingList.copyInto((Object[])_encodings);
        }
        catch (Exception e)
        {
            // Something is wrong, indicate that there are no encoding options
            _encodings = null;
        }
    }

    /**
     * Adds the VideoField to the screen
     */
    private void createUI()
    {
        // Add the video field to the screen
        add(_videoField);
    }

    /**
     * Create a screen used to display a snapshot
     * @param raw A byte array representing an image
     */
    private void createImageScreen( byte[] raw )
    {    
        UiApplication.getUiApplication().popScreen(cameraScreen);
        ImageScreen imageScreen = new ImageScreen( raw );
        UiApplication.getUiApplication().pushScreen( imageScreen );
    }

    /**
     * Sets the index of the encoding in the 'encodingList' Vector
     * @param index The index of the encoding in the 'encodingList' Vector
     */
    public void setIndexOfEncoding(int index)
    {
        _indexOfEncoding = index;
    }

    /**
     * @see net.rim.device.api.ui.Screen#invokeAction(int)
     */   
    protected boolean invokeAction(int action)
    {
        boolean handled = super.invokeAction(action); 

        if(!handled)
        {
            switch(action)
            {
            case ACTION_INVOKE: // Trackball click
            {         
                takePicture();
                return true;
            }
            }
        }        
        return handled;                
    }
}


public static class ImageScreen extends MainScreen
{
    private static final int IMAGE_SCALING = 7;
    private static String FILE_NAME = System.getProperty("fileconn.dir.photos") + "IMAGE";
    private static String EXTENSION = ".bmp";
    private static int _counter;
    private ImageScreen _imageScreen;
    public ImageScreen( final byte[] raw )
    {
        _imageScreen = this;

        setTitle("IMAGE");
        Bitmap image = Bitmap.createBitmapFromBytes( raw, 0, -1, IMAGE_SCALING );

        HorizontalFieldManager hfm1 = new HorizontalFieldManager( Field.FIELD_HCENTER );
        HorizontalFieldManager hfm2 = new HorizontalFieldManager( Field.FIELD_HCENTER );

        BitmapField imageField = new BitmapField( image );
        hfm1.add( imageField );

        ButtonField photoButton = new ButtonField( "Save" );
        photoButton.setChangeListener( new SaveListener(raw) );
        hfm2.add(photoButton);

        ButtonField cancelButton = new ButtonField( "Cancel" );
        cancelButton.setChangeListener( new CancelListener() );
        hfm2.add(cancelButton);

        add( hfm1 );
        add( hfm2 );
    }
    protected boolean invokeAction(int action)
    {
        boolean handled = super.invokeAction(action); 

        if(!handled)
        {
            switch(action)
            {
            case ACTION_INVOKE: // Trackball click.
            {         
                return true;
            }
            }
        }        
        return handled;          
    }

    private class SaveListener implements FieldChangeListener
    {
        private byte[] _raw;

        SaveListener(byte[] raw)
        {
            _raw = raw;
        }

        public void fieldChanged(Field field, int context)
        {
            try
            {       
                FileConnection file = (FileConnection)Connector.open( FILE_NAME + _counter + EXTENSION );
                while( file.exists() )
                {
                    file.close();
                    ++_counter;
                    file = (FileConnection)Connector.open( FILE_NAME + _counter + EXTENSION );
                }

                file.create();
                OutputStream out = file.openOutputStream();
                out.write(_raw);

                out.close();
                file.close();
            }
            catch(Exception e)
            {
            }

            String full_path = FILE_NAME + _counter + EXTENSION;
            setOnBitmapField(full_path);
            selectedImagePath= full_path;
            ++_counter;

            UiApplication.getUiApplication().popScreen( _imageScreen );
        }
    }

    private class CancelListener implements FieldChangeListener
    {
        public void fieldChanged(Field field, int context)
        {
            UiApplication.getUiApplication().popScreen( _imageScreen );
        }
    }
}

=======

public final class EncodingProperties
{   
    private String _format;
    private String _width;
    private String _height;
    private boolean _formatSet;
    private boolean _widthSet;
    private boolean _heightSet;    
    public void setFormat(String format)
    {
        _format = format;
        _formatSet = true;
    } 

public void setWidth(String width)
{
    _width = width;
    _widthSet = true;
}

public void setHeight(String height)
{
    _height = height;
    _heightSet = true;
}    

public String toString()
{
    StringBuffer display = new StringBuffer();

    display.append(_width);
    display.append(" x ");
    display.append(_height);
    display.append(" ");
    display.append(_format);                

    return display.toString();
}
public String getFullEncoding()
{
    StringBuffer fullEncoding = new StringBuffer();

    fullEncoding.append("encoding=");
    fullEncoding.append(_format);

    fullEncoding.append("&width=");
    fullEncoding.append(_width);

    fullEncoding.append("&height=");
    fullEncoding.append(_height);        

    return fullEncoding.toString();
}

public boolean isComplete()
{
    return _formatSet && _widthSet && _heightSet;
}
}