将ImageView(使用Camera Intent)从ImageView保存到设备(Gallery / SdCard)

时间:2017-06-29 21:27:16

标签: android image imageview gallery android-camera-intent

我制作了一个小应用程序,允许打开相机并拍照。之后我在imageView中显示该图片。我的问题是,我想保存我拍摄的图像,然后在imageview上可用。如何将imageview中拍摄和可用的图像保存到我的图库?我目前的代码是:

public class activity_auto extends AppCompatActivity {

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto);

        Button btnCamera= (Button)findViewById(R.id.btnCamera);
        imageView=(ImageView)findViewById(R.id.imageView);
    }

    public void onButtonClicked(View v){
        if(v.getId()==R.id.btnCamera) {
            //starting camera function
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 0);
        }

        if(v.getId()==R.id.goToGPS) {
            Intent intent2 = new Intent(activity_auto.this, function_gps.class );
            startActivity(intent2);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);

        //initialize my imageview
        Bitmap bitmap = (Bitmap)data.getExtras().get("data");
        imageView.setImageBitmap(bitmap);
    }
}

错误日志:

06-30 11:37:25.759 2624-3776/? E/EGL_emulation: eglQueryContext 32c0  EGL_BAD_ATTRIBUTE
06-30 11:37:25.762 2624-3776/? E/EGL_emulation: tid 3776: eglQueryContext(1716): error 0x3004 (EGL_BAD_ATTRIBUTE)
06-30 11:37:26.600 1613-1624/? E/RecoverySystemService: Timed out connecting to uncrypt socket
06-30 11:37:26.600 1613-1624/? E/RecoverySystemService: Failed to connect to uncrypt socket
06-30 11:37:26.665 2412-3061/? E/SystemUpdateService: Failed to call RecoverySystem.cancelScheduledUpdate
                                                      java.lang.reflect.InvocationTargetException
                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                          at xae.c(:com.google.android.gms:134)
                                                          at afuw.d(:com.google.android.gms:195)
                                                          at afuw.p(:com.google.android.gms:2178)
                                                          at afuw.a(:com.google.android.gms:448)
                                                          at afuw.doInBackground(:com.google.android.gms:50475)
                                                          at android.os.AsyncTask$2.call(AsyncTask.java:304)
                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                          at java.lang.Thread.run(Thread.java:761)
                                                       Caused by: java.io.IOException: cancel scheduled update failed
                                                          at android.os.RecoverySystem.cancelScheduledUpdate(RecoverySystem.java:555)
                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                          at xae.c(:com.google.android.gms:134) 
                                                          at afuw.d(:com.google.android.gms:195) 
                                                          at afuw.p(:com.google.android.gms:2178) 
                                                          at afuw.a(:com.google.android.gms:448) 
                                                          at afuw.doInBackground(:com.google.android.gms:50475) 
                                                          at android.os.AsyncTask$2.call(AsyncTask.java:304) 
                                                          at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
                                                          at java.lang.Thread.run(Thread.java:761) 
06-30 11:37:26.666 2412-3061/? E/SystemUpdateTask: exception trying to cancel scheduled update
                                                   java.io.IOException: Failed to invoke RecoverySystem.cancelScheduledUpdate
                                                       at xae.c(:com.google.android.gms:140)
                                                       at afuw.d(:com.google.android.gms:195)
                                                       at afuw.p(:com.google.android.gms:2178)
                                                       at afuw.a(:com.google.android.gms:448)
                                                       at afuw.doInBackground(:com.google.android.gms:50475)
                                                       at android.os.AsyncTask$2.call(AsyncTask.java:304)
                                                       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                       at java.lang.Thread.run(Thread.java:761)
06-30 11:37:33.447 3100-3100/com.group6.travlhoe E/AndroidRuntime: FATAL EXCEPTION: main
                                                                   Process: com.group6.travlhoe, PID: 3100
                                                                   java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.group6.travlhoe/com.group6.travlhoe.activity_auto}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
                                                                       at android.app.ActivityThread.deliverResults(ActivityThread.java:4053)
                                                                       at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096)
                                                                       at android.app.ActivityThread.-wrap20(ActivityThread.java)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
                                                                       at com.group6.travlhoe.activity_auto.onActivityResult(activity_auto.java:105)
                                                                       at android.app.Activity.dispatchActivityResult(Activity.java:6915)
                                                                       at android.app.ActivityThread.deliverResults(ActivityThread.java:4049)
                                                                       at android.app.ActivityThread.handleSendResult(ActivityThread.java:4096) 
                                                                       at android.app.ActivityThread.-wrap20(ActivityThread.java) 
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1516) 
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                       at android.os.Looper.loop(Looper.java:154) 
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6077) 
                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
06-30 11:37:40.070 3243-3264/? E/AppDataSearchHelper: Couldn't find corpus 'playlists'

3 个答案:

答案 0 :(得分:0)

你有很多事可做。

您需要清单和运行时的存储永久性,这本身就是一个主题。

您需要处理外部存储以获取和使用该文件夹来编写照片,并使用ContentResolver将照片从cammera存储的位置复制到您应用的文件夹中。

如果您想在图库中查看照片,您还需要使用MediaScannerConnection,以便对其进行编目并使用户能够快速看到。

我建议你按照一些教程来学习如何做到这一切。

Commonsware 搜索 CWAC Cammera 。他们在Github有一个项目,你可以结账,如果你谷歌多一点,你应该找到一个教程解释该项目的过程的每个步骤。

答案 1 :(得分:0)

所以,我找到了将摄像头意图添加到您的画廊中的最佳方式:

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class activity_auto extends AppCompatActivity {

    private BottomNavigationView bottomNavigationView;


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto);

        ImageButton btnCamera= (ImageButton)findViewById(R.id.btnCamera);

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
    }

    public void onButtonClicked(View v){
        if(v.getId()==R.id.btnCamera) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            String pictureName= getPictureName();
            File imageFile=  new File(pictureDirectory,pictureName);

            //URI weil putExtra sonst nicht mit File elementen klar kommt!
            Uri pictureUri = Uri.fromFile(imageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);

            startActivityForResult(intent, 0);
        }
        if(v.getId()==R.id.goToGPS) {
            Intent intent2 = new Intent(activity_auto.this, function_gps.class );
            startActivity(intent2);
        }
    }
    private String getPictureName() {
        SimpleDateFormat tst = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timestamp = tst.format(new Date());
        return "Rechnung"+ timestamp + ".jpg";
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

       // Bitmap bitmap = (Bitmap)data.getExtras().get("data");

        //imageView.setImageBitmap(bitmap);
    }
}`enter code here`

答案 2 :(得分:-1)

编写此代码以保存图像

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
      super.onActivityResult(requestCode, resultCode, data);
      Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG,90,bytes);
            File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
            FileOutputStream fo;
            try{
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }
            imageView.setImageBitmap(thumbnail);


            imageView.setDrawingCacheEnabled(true);
            Bitmap b = imageView.getDrawingCache();
            MediaStore.Images.Media.insertImage(getContentResolver(),b,"Pics","Task5");
            Toast.makeText(getApplicationContext(),"Image Saved",Toast.LENGTH_LONG).show();
    }

在Manifest.xml中编写此权限

   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
   <uses-permission android:name="android.permission.CAMERA"/>

转到设置 - &gt;应用 - &gt; “你的应用” - &gt;权限。允许摄像头和存储访问。