【问题标题】:How to distinguish whether the image is coming from gallery or camera in android?如何区分图像是来自android中的画廊还是相机?
【发布时间】:2014-05-14 14:01:37
【问题描述】:

我正在制作一个应用程序,我可以在其中从图库中选择图像,或者我可以从相机中获取图像,并且我正在使用所选图像移动到下一个活动。我想区分图像是来自图库还是来自相机.我不知道该怎么做。我正在提供我的代码。请帮助我如何做到这一点。

我的第一个活动是

import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;



  public class LauncherActivity extends Activity 
   {
 private static final int CAMERA_REQUEST = 1888; 
 private static int RESULT_LOAD_IMAGE = 1;
 ImageButton camera;
 ImageButton gallery;
 ImageView gallery_image;

 protected void onCreate(Bundle paramBundle)
 {
 super.onCreate(paramBundle);
 setContentView(R.layout.launcher);
 gallery = (ImageButton)findViewById(R.id.select_photo);
 camera = (ImageButton)findViewById(R.id.take_photo);





   gallery.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub        
            Intent gallery_intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(gallery_intent, RESULT_LOAD_IMAGE);
     }
    });

     camera.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub        
                    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                    startActivityForResult(cameraIntent, CAMERA_REQUEST); 
    }
});

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



  if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)     {



      Uri selectedImage = data.getData();

      String[] filePathColumn = { MediaStore.Images.Media.DATA };



      Cursor cursor = getContentResolver().query(selectedImage,
              filePathColumn, null, null, null);
      cursor.moveToFirst();

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      String picturePath = cursor.getString(columnIndex);
      cursor.close();
      Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
      intent.putExtra("path", picturePath);
      startActivity(intent); 

    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK && data!=null) {  

      Bitmap photo_from_camera = (Bitmap) data.getExtras().get("data"); 

      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      photo_from_camera.compress(Bitmap.CompressFormat.PNG, 100, stream);
      byte[] byteArray = stream.toByteArray();
      Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
      intent.putExtra("image", byteArray);
      startActivity(intent);


    }  
  }
  }

我的第二个活动是

   public class MainActivity extends Activity 
   {
   Bitmap scaled;
 protected void onCreate(Bundle paramBundle)
  {
  super.onCreate(paramBundle);
  setContentView(R.layout.activity_main);


   if(//condition to The image coming from gallery)
   {
   Bundle extras=getIntent().getExtras();
   String picturePath=extras.getString("path");
  scaled=BitmapFactory.decodeFile(picturePath);
  //the things i have to do with bitmap that i know
   }    
  if(//Condition to the image coming from camera)
  {
    Bundle extras = getIntent().getExtras();
   byte[] byteArray = extras.getByteArray("image");
   Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
  scaled = Bitmap.createScaledBitmap(bitmap, width, height, true);
  //the things i have to do with bitmap that i know
  }
  }
   }

这里我没有在 if 语句中编写条件的代码。请帮助我。提前致谢。

【问题讨论】:

    标签: android gallery android-camera-intent


    【解决方案1】:
    startActivityForResult(cameraIntent, CAMERA_REQUEST); 
    startActivityForResult(gallery_intent, RESULT_LOAD_IMAGE);
    

    关于您的请求代码,您可以区分图像来自图库或相机

     boolean gallery;
    
         if(requestCode == CAMERA_REQUEST){
            //then image from camera
    
    gallery=true;
        galleryIntent intent = new Intent(LauncherActivity.this, MainActivity.class);
              intent.putExtra("path", picturePath);  
             intent.putExtra("isfrom", gallery); 
        startActivity(intent);
            }
            if(requestCode == RESULT_LOAD_IMAGE){
        galleryIntent intent = new Intent(LauncherActivity.this, MainActivity.class);
              intent.putExtra("path", picturePath);  
             intent.putExtra("isfrom", gallery); 
        startActivity(intent);
            //then image from gallery
            }
    

    在第二个活动中,您可以从意图中获取布尔值。如果它是来自图库的真实图像

    【讨论】:

    • 它用于在同一个活动中进行区分。我正在使用所选图像进行第二个活动。在第二个活动中,我想区分。这在那里不起作用。
    • 你可以在第一个活动 onActivityResult() 中做一个标志,并在第二个活动中使用它
    • 你能详细告诉我吗?
    • Intent intent = new Intent(LauncherActivity.this, MainActivity.class); intent.putExtra("路径", picturePath); intent.putExtra("isfrom", 画廊);开始活动(意图);
    • @rajahsekar 他不会理解,因为他不知道如何编程(至少在 android 中)。你的回答很好,顺其自然。
    【解决方案2】:
    // try this way,hope this will help you...
    
    launcher.xml
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1">
            <ImageView
                android:id="@+id/imageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <Button
                android:id="@+id/select_photo"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="Gallery"/>
    
            <Button
                android:id="@+id/take_photo"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="Camera"/>
        </LinearLayout>
    </LinearLayout>
    
    activity_main
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">
    
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"/>
    </LinearLayout>
    
    LauncherActivity.java
    public class LauncherActivity extends Activity {
    
        private static final int CAMERA_REQUEST = 1;
        private static final int RESULT_LOAD_IMAGE = 2;
        Button camera;
        Button gallery;
        ImageView imageView;
        private String imgPath;
    
        protected void onCreate(Bundle paramBundle) {
            super.onCreate(paramBundle);
            setContentView(R.layout.launcher);
            gallery = (Button) findViewById(R.id.select_photo);
            camera = (Button) findViewById(R.id.take_photo);
            imageView = (ImageView) findViewById(R.id.imageView);
    
    
            gallery.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, ""), RESULT_LOAD_IMAGE);
                }
            });
    
            camera.setOnClickListener(new View.OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
                    startActivityForResult(intent, CAMERA_REQUEST);
                }
            });
    
        }
    
        public Uri setImageUri() {
            // Store image in dcim
            File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
            Uri imgUri = Uri.fromFile(file);
            this.imgPath = file.getAbsolutePath();
            return imgUri;
        }
    
        public String getImagePath() {
            return imgPath;
        }
    
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == RESULT_LOAD_IMAGE) {
                    imageView.setImageBitmap(decodeFile(getAbsolutePath(data.getData())));
                    Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
                    intent.putExtra("path", getAbsolutePath(data.getData()));
                    intent.putExtra("from", "Gallery");
                    startActivity(intent);
                } else if (requestCode == CAMERA_REQUEST) {
                    imageView.setImageBitmap(decodeFile(getImagePath()));
                    Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
                    intent.putExtra("path", getImagePath());
                    intent.putExtra("from", "Camera");
                    startActivity(intent);
                }
            }
    
        }
    
        public String getAbsolutePath(Uri uri) {
            if(Build.VERSION.SDK_INT >= 19){
                String id = uri.getLastPathSegment().split(":")[1];
                final String[] imageColumns = {MediaStore.Images.Media.DATA };
                final String imageOrderBy = null;
                Uri tempUri = getUri();
                Cursor imageCursor = getContentResolver().query(tempUri, imageColumns,
                        MediaStore.Images.Media._ID + "="+id, null, imageOrderBy);
                if (imageCursor.moveToFirst()) {
                    return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                }else{
                    return null;
                }
            }else{
                String[] projection = { MediaStore.MediaColumns.DATA };
                Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
                if (cursor != null) {
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                    cursor.moveToFirst();
                    return cursor.getString(column_index);
                } else
                    return null;
            }
    
        }
    
        private Uri getUri() {
            String state = Environment.getExternalStorageState();
            if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
                return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
    
            return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        }
    
        public Bitmap decodeFile(String path) {
            try {
                // Decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(path, o);
                // The new size we want to scale to
                final int REQUIRED_SIZE = 1024;
    
                // Find the correct scale value. It should be the power of 2.
                int scale = 1;
                while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                    scale *= 2;
    
                // Decode with inSampleSize
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                return BitmapFactory.decodeFile(path, o2);
            } catch (Throwable e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
    MainActivity.java
    public class MainActivity extends Activity {
    
    
        ImageView imageView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            imageView = (ImageView) findViewById(R.id.imageView);
            Toast.makeText(this,getIntent().getStringExtra("from"),Toast.LENGTH_SHORT)
            .show();
            imageView.setImageBitmap(decodeFile(getIntent().getStringExtra("path")));
    
        }
    
        public Bitmap decodeFile(String path) {
            try {
                // Decode image size
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(path, o);
                // The new size we want to scale to
                final int REQUIRED_SIZE = 1024;
    
                // Find the correct scale value. It should be the power of 2.
                int scale = 1;
                while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
                    scale *= 2;
    
                // Decode with inSampleSize
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                return BitmapFactory.decodeFile(path, o2);
            } catch (Throwable e) {
                e.printStackTrace();
            }
            return null;
    
        }
    }
    
    Note : please not forget this permission in AndroidManifest.xml
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      • 2015-03-03
      • 2014-07-24
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 2017-02-25
      相关资源
      最近更新 更多