1. 程式人生 > >Android——獲取系統圖片/拍照/獲取圖片路徑並顯示的Demo

Android——獲取系統圖片/拍照/獲取圖片路徑並顯示的Demo

主要問題是,在網上找到的很多Demo在Sony和喪門星上無法獲取圖片的真實路徑,下面demo記錄的方法可以顯示image並獲取圖片路徑

1. Java Code

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
    private static String srcPath;
    private static int RESULT_LOAD_IMAGE = 2;  
    
    private Button getPhotosBtn;
    private Button takePhotoBtn;
    private ImageView showImage;
	
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init ();
	}
	
	 @Override  
	    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
	        super.onActivityResult(requestCode, resultCode, data);  
	        if (resultCode == Activity.RESULT_OK) {  
	            switch(requestCode) {  
	            //Take Photos
	                case 1:  
	                    Bundle extras = data.getExtras();  
	                    Bitmap b = (Bitmap) extras.get("data");  
	                    showImage.setImageBitmap(b);  
	                    
	                   String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());  
	                    String fileNmae = Environment.getExternalStorageDirectory().toString()+File.separator+"OCR/image/"+name+".jpg";  
	                    srcPath = fileNmae;  
	                    System.out.println(srcPath+"--save from taking photos");  
	                    File myCaptureFile =new File(fileNmae);  
	                    try {  
	                        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
	                            if(!myCaptureFile.getParentFile().exists()){  
	                                myCaptureFile.getParentFile().mkdirs();  
	                            }  
	                            BufferedOutputStream bos;  
	                            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));  
	                            b.compress(Bitmap.CompressFormat.JPEG, 80, bos);  
	                            bos.flush();  
	                            bos.close();  
	                        }else{  
	                        	Toast toast= Toast.makeText(MainActivity.this, "儲存失敗,SD卡無效", Toast.LENGTH_SHORT);  
	                            toast.setGravity(Gravity.CENTER, 0, 0);  
	                            toast.show();  
	                        }  
	                    } catch (FileNotFoundException e) {  
	                        e.printStackTrace();  
	                    } catch (IOException e) {  
	                        e.printStackTrace();  
	                    }  
	                    break;  
	           //Load Local Photos
	                case 2:  
	                    Uri uri = data.getData();  
	                    showImage.setImageURI(uri);  
	                    ContentResolver cr = this.getContentResolver();  
	                    Cursor c = cr.query(uri, null, null, null, null);  
	                    c.moveToFirst();  
	                    //這是獲取的圖片儲存在sdcard中的位置  
	                    srcPath = c.getString(c.getColumnIndex("_data"));  
	                    System.out.println(srcPath+"----------儲存路徑2"); 
	                    break;  
	                	
	                default:  
	                    break;  
	            };  
	        }  

	    }  
	
	 private void init(){
	    getPhotosBtn = (Button) findViewById(R.id.picturePickerButton);
	    takePhotoBtn = (Button) findViewById(R.id.takePhotoButton);
	    showImage = (ImageView) findViewById(R.id.showPicture_ImageView);
	    
	    getPhotosBtn.setOnClickListener(this);
	    takePhotoBtn.setOnClickListener(this);
	 }
	 
	 @Override
	 public void onClick(View v) {  
	        switch(v.getId()){  
	            case R.id.picturePickerButton:  
	               //Important!
	                Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
                    startActivityForResult(intent, 2);
                    
	                break;  
	            case R.id.takePhotoButton:  
	                Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  
	                startActivityForResult(it, 1);  
	                break;  
	        }  
	    }  
	 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

2. Layout Code

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.clare.MainActivity" >
    
    <LinearLayout
	    android:id="@+id/imageView_layout"
	    android:layout_width="match_parent"
	    android:layout_height="0dp"
	    android:layout_weight="1"
	    android:background="@color/lavenderblush">
	    <ImageView 
	    	android:id="@+id/showPicture_ImageView"
			android:layout_height="match_parent"
			android:layout_width="match_parent">
		</ImageView>
	</LinearLayout>
	<LinearLayout
	    android:id="@+id/buttonsLayout"
	    android:layout_gravity="bottom"
	    android:layout_width="match_parent"
	    android:layout_height="30dp"
	    android:orientation="horizontal">
		<Button
       		android:id="@+id/picturePickerButton"
	   		android:layout_width="0dp"
	   		android:layout_height="30dp"
	   		android:layout_weight="1"
	   		android:textColor="@color/blueviolet"
	   		android:background="@color/white"
	   		android:text="@string/choose_picture"/>
		<Button
       		android:id="@+id/takePhotoButton"
	   		android:layout_width="0dp"
	   		android:layout_height="30dp"
	   		android:layout_weight="1"
	   		android:textColor="@color/blueviolet"
	   		android:background="@color/white"
	   		android:text="@string/take_picture"/>	
	</LinearLayout>
</LinearLayout>