简体   繁体   中英

Android Camera Taken Picture is not saving to sd card

I have developed a simple android application in Eclipse for Opening camera and taking photo and saving this to Sdcard but when i start camera and take picture and when try to save my application got error that Application ha stopped unfortunately .Is Kindly Help me is there any issue in my code file here is my code for saving and taking picture from camera.

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);
    }
}

Kindly Guide me what exactly I am missing in my code or any other way to get out of this problem

Update

Here is My Manifest File Code

<?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>

But cam is Not Still saving Image to gallery and application Stooped unfortunately

Sir Here IS My Error Log

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

try this code::::

 @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();
            }
    }

Updated:::: Add the below permissions n manifeast file

<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" />

Try this,

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
      }



  }

Try following code set. It works for me...

With in the onActivityResult method call following code set.

    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());
    }

Matrix part is not relevant to your problem directly. Then you will need following two methods also.

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;
}   

Be careful with the variable name I have given. :-)

In the Manifest don't forget to give following permission too

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM