0

我已经在 Eclipse 中开发了一个简单的 android 应用程序,用于打开相机并拍照并将其保存到 SD 卡,但是当我启动相机并拍照时,当我尝试保存我的应用程序时出现错误,应用程序已不幸停止。请帮助我有没有我的代码文件中的问题是我用于保存和从相机拍照的代码。

package cam.cam.pkg;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class CAMActivity extends Activity {
    private static final int REQUEST_CODE = 1;
    private Button button_1;
    public int TAKE_PICTURE = 1;
    private ImageView image_view;
    private Bitmap bitmap;
    /** Called when the activity is first created. */
    @Override
       public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

         image_view = (ImageView) findViewById(R.id.result);
         button_1 = (Button) findViewById(R.id.button1);

        button_1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                startActivityForResult(intent, TAKE_PICTURE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
            try {
                // We need to recyle unused bitmaps
                if (bitmap != null) {
                    bitmap.recycle();
                }
                InputStream stream = getContentResolver().openInputStream(
                        data.getData());
                bitmap = BitmapFactory.decodeStream(stream);
                stream.close();
                image_view.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

请指导我在我的代码中究竟缺少什么或任何其他方式来解决这个问题

更新

这是我的清单文件代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cam.cam.pkg"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".CAMActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

但是 cam 仍然没有将图像保存到画廊和应用程序中 不幸的是,Sooped

先生,这是我的错误日志

org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.IllegalArgumentException: Argument not valid)
    at org.eclipse.swt.SWT.error(SWT.java:4282)
    at org.eclipse.swt.SWT.error(SWT.java:4197)
    at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:138)
    at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4140)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3757)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:825)
    at org.eclipse.jface.window.Window.open(Window.java:801)
    at org.eclipse.jface.dialogs.MessageDialog.open(MessageDialog.java:334)
    at org.eclipse.ui.internal.ide.dialogs.InternalErrorDialog.open(InternalErrorDialog.java:80)
    at org.eclipse.ui.internal.ide.IDEWorkbenchErrorHandler.openQuestionDialog(IDEWorkbenchErrorHandler.java:199)
    at org.eclipse.ui.internal.ide.IDEWorkbenchErrorHandler.handleException(IDEWorkbenchErrorHandler.java:154)
    at org.eclipse.ui.internal.ide.IDEWorkbenchErrorHandler.access$0(IDEWorkbenchErrorHandler.java:146)
    at org.eclipse.ui.internal.ide.IDEWorkbenchErrorHandler$1.runInUIThread(IDEWorkbenchErrorHandler.java:121)
    at org.eclipse.ui.progress.UIJob$1.run(UIJob.java:95)
    at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
    at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
    at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4140)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3757)
    at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2701)
    at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2665)
    at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2499)
    at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:679)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:668)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:123)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:344)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
Caused by: java.lang.IllegalArgumentException: Argument not valid
    at org.eclipse.swt.SWT.error(SWT.java:4263)
    at org.eclipse.swt.SWT.error(SWT.java:4197)
    at org.eclipse.swt.SWT.error(SWT.java:4168)
    at org.eclipse.swt.graphics.GC.drawImage(GC.java:958)
    at org.eclipse.swt.graphics.GC.drawImage(GC.java:943)
    at com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageOverlay.paint(ImageOverlay.java:214)
    at com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas.onPaint(LayoutCanvas.java:729)
    at com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas.access$0(LayoutCanvas.java:723)
    at com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas$1.paintControl(LayoutCanvas.java:277)
    at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:229)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1077)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1062)
    at org.eclipse.swt.widgets.Composite.WM_PAINT(Composite.java:1564)
    at org.eclipse.swt.widgets.Control.windowProc(Control.java:4585)
    at org.eclipse.swt.widgets.Canvas.windowProc(Canvas.java:341)
    at org.eclipse.swt.widgets.Display.windowProc(Display.java:4985)
    at org.eclipse.swt.internal.win32.OS.RedrawWindow(Native Method)
    at org.eclipse.swt.widgets.Control.update(Control.java:4380)
    at org.eclipse.swt.widgets.Display.update(Display.java:4846)
    at org.eclipse.ui.internal.LegacyAnimationFeedback.renderStep(LegacyAnimationFeedback.java:60)
    at org.eclipse.ui.internal.AnimationEngine.updateDisplay(AnimationEngine.java:131)
    at org.eclipse.ui.internal.AnimationEngine$1.run(AnimationEngine.java:120)
    at org.eclipse.ui.internal.UILockListener.doPendingWork(UILockListener.java:164)
    at org.eclipse.ui.internal.UISynchronizer$3.run(UISynchronizer.java:158)
    at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
    at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
    ... 35 more
4

4 回答 4

0
if (requestCode == CAMERA) {
                    Log.d("log", " request code camera " + requestCode);
                    final File file = getTempFile(this);
                    try {
                        selImagePath = file.getAbsolutePath();
                        m_bmOCRBitmap = Media.getBitmap(getContentResolver(),
                                Uri.fromFile(file));
                        img_pht.setImageBitmap(m_bmOCRBitmap);
                        hideMenu();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();

                    }
                } 


try this code...
于 2012-05-25T11:45:27.363 回答
0

尝试以下代码集。这个对我有用...

onActivityResult方法调用下面的代码集中。

    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

    Matrix matrix = new Matrix();
    matrix.postRotate(90);

    int width = bitmap.getWidth();
    int height = bitmap.getHeight();

    Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);

    // Display the captured image oon your screen
    capturedImageView.setImageBitmap(resizedBitmap);

    getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
    if (pictureFile == null){
        Log.d(TAG, "Error creating media file, check storage permissions: ");
        return;
    }

    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        fos.write(data);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }

矩阵部分与您的问题没有直接关系。然后,您还需要以下两种方法。

private static Uri getOutputMediaFileUri(int type){
      return Uri.fromFile(getOutputMediaFile(type));
}

private static File getOutputMediaFile(int type){

    File mediaStorageDir = new File(imagesSavingSubfolderPath);

    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    if (type == MEDIA_TYPE_IMAGE){
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}   

小心我给出的变量名。:-)

在清单中也不要忘记给予以下许可

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
于 2012-05-25T11:15:35.060 回答
0

试试这个代码::::

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
            try {
            image_view.setImageUri(Uri.parse(data.getDataString()));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

更新:::: 添加以下权限 n 清单文件

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
于 2012-05-25T10:50:37.210 回答
0

尝试这个,

public class Camera extends Activity 
  {
 private static final int CAMERA_REQUEST = 1888;
 private String selectedImagePath;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
    startActivityForResult(cameraIntent, CAMERA_REQUEST);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (resultCode == RESULT_OK) {
        if (requestCode == CAMERA_REQUEST) 
        { 
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
            Random randomGenerator = new Random();randomGenerator.nextInt();
            String newimagename=randomGenerator.toString()+".jpg";
            File f = new File(Environment.getExternalStorageDirectory()
                                    + File.separator + newimagename);
            try {
                f.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //write the bytes in file

            try {
                fo = new FileOutputStream(f.getAbsoluteFile());
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                fo.write(bytes.toByteArray());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                uri=f.getAbsolutePath(); 
    //this is the url that where you are saved the image
      }



  }
于 2012-05-25T10:54:31.683 回答