android 在SDCard获取图片

主类:

package com.dianxing.xiawenqaun;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class TestPicture extends Activity {
	private final int INSERT_PICTURE_DIALOG = 1;
	private final int SHOW_PROGRESS_DIALOG = 0;
	private final int TAKE_PICTURE = 0;
	private final int LOCAL_PICTURE = 1;
	private final int CROP_IMAGE = 3;
	private final int CHANGING_SUCCESSED = 100;
	private final int ICON_SIZE = 96;	
	private File mFilePath;
	
	public static final String IMAGEDATA  = "imageData ";
	public static final String IMAGE_FILESUFFIX = "imageFileSuffix";
	
	private final String IMAGE_DATA = "data";
	// 文件保存路径
	public static final String SAVE_FILE_PATH_DIRECTORY = Environment
			.getExternalStorageDirectory().getAbsolutePath() + "/" + "dianxing";
	private ImageView imageView;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        imageView = (ImageView) this.findViewById(R.id.imageView);
        
        
        Button button = (Button) this.findViewById(R.id.bnt);
        button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialog(INSERT_PICTURE_DIALOG);
				
			}
		});
        
        imageView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				
			}
		});
    }

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case SHOW_PROGRESS_DIALOG: {
			final ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("头像上传");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.setOnKeyListener(new OnKeyListener() {
				@Override
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
					if (keyCode == KeyEvent.KEYCODE_BACK) {
						TestPicture.this.removeDialog(SHOW_PROGRESS_DIALOG);
					}
					return false;
				}
			});
			return dialog;
		}
		case INSERT_PICTURE_DIALOG: {
			return new AlertDialog.Builder(this).setTitle(R.string.str_modify_head_portrait)
					.setItems(R.array.insert_picture, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which) {
							case TAKE_PICTURE: {
								if (checkSDCard()) {
									if (checkFileDirectory()) {
										final Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
										mFilePath = new File(SAVE_FILE_PATH_DIRECTORY, ""
												+ System.currentTimeMillis() + ".jpg");
										final Uri localUri = Uri.fromFile(mFilePath);
										i.putExtra(MediaStore.EXTRA_OUTPUT, localUri);
										startActivityForResult(i, TAKE_PICTURE);
									} else {
										System.out.println("no found Directory");
									}
								} else {
									Toast.makeText(TestPicture.this, "SDCard不存在", 0).show();
								}
								break;
							}
							case LOCAL_PICTURE: {
								if (checkSDCard()) {
									final Uri localUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
									final Intent intent = new Intent(Intent.ACTION_PICK, localUri);
									startActivityForResult(intent, LOCAL_PICTURE);
								} else {
									Toast.makeText(TestPicture.this, "SDCard不存在", 0).show();
								}
								break;
							}
							}
							dismissDialog(INSERT_PICTURE_DIALOG);
						}
					}).create();
		}
		}
		return super.onCreateDialog(id);
	}
    
	/**
	 * 检查SD卡是否存在
	 * 
	 * @return
	 */
	public static boolean checkSDCard() {
		final String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}
    
	/**
	 * check file directory exists.
	 * 
	 * @return boolean
	 */
	public static boolean checkFileDirectory() {
		final File dir = new File(SAVE_FILE_PATH_DIRECTORY);
		if (!dir.exists()) {
			final boolean isMkdirs = dir.mkdirs();
			return isMkdirs;
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case LOCAL_PICTURE: {
				final Uri uri = data.getData();
				System.out.println("LOCAL_PICTURE uri = " + uri);
				gotoCropImageActivity(uri);
				break;
			}
			case TAKE_PICTURE: {
				// 重新扫描sd卡
				showDialog(SHOW_PROGRESS_DIALOG);
				new Thread(new Runnable() {

					@Override
					public void run() {
						final Uri scanFile = Uri.parse("file://" + mFilePath);
						sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, scanFile));
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						getHeadSettingHandler.sendEmptyMessage(CHANGING_SUCCESSED);
					}
				}).start();
				break;
			}
			case CROP_IMAGE: {
				
				Bundle bundle = data.getExtras();
				imageView.setImageBitmap((Bitmap)bundle.getParcelable(IMAGE_DATA));
				
				// 在这里进行联网,把图像的数据上传至服务器
				
				break;
			}
			default:
				break;
			}
		}
	}
	
	/**
	 * 跳转裁切界面
	 * 
	 * @param uri
	 */
	private void gotoCropImageActivity(Uri uri) {
		if (uri == null) {
			Uri imgUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
			ContentResolver cr = getContentResolver();

			Cursor cursor = cr.query(imgUri, null, MediaStore.Images.Media.DISPLAY_NAME, null, null);
			if (cursor != null && cursor.getCount() > 0) {
				final int countryIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
				cursor.moveToLast();
				long id = cursor.getLong(countryIndex);
				uri = ContentUris.withAppendedId(imgUri, id);
			}
		}

		 final Intent intent = getCropImageIntent(uri);
         startActivityForResult(intent, CROP_IMAGE);
	}
	
	public Intent getCropImageIntent(Uri photoUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(photoUri, "image/*");
        intent.putExtra("crop", "true");
        // 设定长宽比
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 设定输出位图大小
        intent.putExtra("outputX", ICON_SIZE);
        intent.putExtra("outputY", ICON_SIZE);
        // true返回一个位图,false直接保存剪裁这张图像
        intent.putExtra("return-data", true);
        return intent;
    }
	
	private Handler getHeadSettingHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int what = msg.what;
			switch (what) {
			case CHANGING_SUCCESSED:
				removeDialog(SHOW_PROGRESS_DIALOG);
				gotoCropImageActivity(null);
				break;
			}
		}
	};
}
 
package com.dianxing.xiawenqaun;

public class Base64 {
    private static final byte[] encodingTable = {
            (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E',
            (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J',
            (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O',
            (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T',
            (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y',
            (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd',
            (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i',
            (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
            (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's',
            (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x',
            (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2',
            (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
            (byte) '8', (byte) '9', (byte) '+', (byte) '/'
        };
    private static final byte[] decodingTable;
    static {
        decodingTable = new byte[128];
        for (int i = 0; i < 128; i++) {
            decodingTable[i] = (byte) -1;
        }
        for (int i = 'A'; i <= 'Z'; i++) {
            decodingTable[i] = (byte) (i - 'A');
        }
        for (int i = 'a'; i <= 'z'; i++) {
            decodingTable[i] = (byte) (i - 'a' + 26);
        }
        for (int i = '0'; i <= '9'; i++) {
            decodingTable[i] = (byte) (i - '0' + 52);
        }
        decodingTable['+'] = 62;
        decodingTable['/'] = 63;
    }
    public static byte[] encode(byte[] data) {
        byte[] bytes;
        int modulus = data.length % 3;
        if (modulus == 0) {
            bytes = new byte[(4 * data.length) / 3];
        } else {
            bytes = new byte[4 * ((data.length / 3) + 1)];
        }
        int dataLength = (data.length - modulus);
        int a1;
        int a2;
        int a3;
        for (int i = 0, j = 0; i < dataLength; i += 3, j += 4) {
            a1 = data[i] & 0xff;
            a2 = data[i + 1] & 0xff;
            a3 = data[i + 2] & 0xff;
            bytes[j] = encodingTable[(a1 >>> 2) & 0x3f];
            bytes[j + 1] = encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f];
            bytes[j + 2] = encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f];
            bytes[j + 3] = encodingTable[a3 & 0x3f];
        }
        int b1;
        int b2;
        int b3;
        int d1;
        int d2;
        switch (modulus) {
        case 0: /* nothing left to do */
            break;
        case 1:
            d1 = data[data.length - 1] & 0xff;
            b1 = (d1 >>> 2) & 0x3f;
            b2 = (d1 << 4) & 0x3f;
            bytes[bytes.length - 4] = encodingTable[b1];
            bytes[bytes.length - 3] = encodingTable[b2];
            bytes[bytes.length - 2] = (byte) '=';
            bytes[bytes.length - 1] = (byte) '=';
            break;
        case 2:
            d1 = data[data.length - 2] & 0xff;
            d2 = data[data.length - 1] & 0xff;
            b1 = (d1 >>> 2) & 0x3f;
            b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
            b3 = (d2 << 2) & 0x3f;
            bytes[bytes.length - 4] = encodingTable[b1];
            bytes[bytes.length - 3] = encodingTable[b2];
            bytes[bytes.length - 2] = encodingTable[b3];
            bytes[bytes.length - 1] = (byte) '=';
            break;
        }
        return bytes;
    }
    public static byte[] decode(byte[] data) {
        byte[] bytes;
        byte b1;
        byte b2;
        byte b3;
        byte b4;
        data = discardNonBase64Bytes(data);
        if (data[data.length - 2] == '=') {
            bytes = new byte[(((data.length / 4) - 1) * 3) + 1];
        } else if (data[data.length - 1] == '=') {
            bytes = new byte[(((data.length / 4) - 1) * 3) + 2];
        } else {
            bytes = new byte[((data.length / 4) * 3)];
        }
        for (int i = 0, j = 0; i < (data.length - 4); i += 4, j += 3) {
            b1 = decodingTable[data[i]];
            b2 = decodingTable[data[i + 1]];
            b3 = decodingTable[data[i + 2]];
            b4 = decodingTable[data[i + 3]];
            bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[j + 2] = (byte) ((b3 << 6) | b4);
        }
        if (data[data.length - 2] == '=') {
            b1 = decodingTable[data[data.length - 4]];
            b2 = decodingTable[data[data.length - 3]];
            bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
        } else if (data[data.length - 1] == '=') {
            b1 = decodingTable[data[data.length - 4]];
            b2 = decodingTable[data[data.length - 3]];
            b3 = decodingTable[data[data.length - 2]];
            bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
        } else {
            b1 = decodingTable[data[data.length - 4]];
            b2 = decodingTable[data[data.length - 3]];
            b3 = decodingTable[data[data.length - 2]];
            b4 = decodingTable[data[data.length - 1]];
            bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
        }
        return bytes;
    }
    public static byte[] decode(String data) {
        byte[] bytes;
        byte b1;
        byte b2;
        byte b3;
        byte b4;
        data = discardNonBase64Chars(data);
        if (data.charAt(data.length() - 2) == '=') {
            bytes = new byte[(((data.length() / 4) - 1) * 3) + 1];
        } else if (data.charAt(data.length() - 1) == '=') {
            bytes = new byte[(((data.length() / 4) - 1) * 3) + 2];
        } else {
            bytes = new byte[((data.length() / 4) * 3)];
        }
        for (int i = 0, j = 0; i < (data.length() - 4); i += 4, j += 3) {
            b1 = decodingTable[data.charAt(i)];
            b2 = decodingTable[data.charAt(i + 1)];
            b3 = decodingTable[data.charAt(i + 2)];
            b4 = decodingTable[data.charAt(i + 3)];
            bytes[j] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[j + 1] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[j + 2] = (byte) ((b3 << 6) | b4);
        }
        if (data.charAt(data.length() - 2) == '=') {
            b1 = decodingTable[data.charAt(data.length() - 4)];
            b2 = decodingTable[data.charAt(data.length() - 3)];
            bytes[bytes.length - 1] = (byte) ((b1 << 2) | (b2 >> 4));
        } else if (data.charAt(data.length() - 1) == '=') {
            b1 = decodingTable[data.charAt(data.length() - 4)];
            b2 = decodingTable[data.charAt(data.length() - 3)];
            b3 = decodingTable[data.charAt(data.length() - 2)];
            bytes[bytes.length - 2] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 1] = (byte) ((b2 << 4) | (b3 >> 2));
        } else {
            b1 = decodingTable[data.charAt(data.length() - 4)];
            b2 = decodingTable[data.charAt(data.length() - 3)];
            b3 = decodingTable[data.charAt(data.length() - 2)];
            b4 = decodingTable[data.charAt(data.length() - 1)];
            bytes[bytes.length - 3] = (byte) ((b1 << 2) | (b2 >> 4));
            bytes[bytes.length - 2] = (byte) ((b2 << 4) | (b3 >> 2));
            bytes[bytes.length - 1] = (byte) ((b3 << 6) | b4);
        }
        return bytes;
    }
    private static byte[] discardNonBase64Bytes(byte[] data) {
        byte[] temp = new byte[data.length];
        int bytesCopied = 0;
        for (int i = 0; i < data.length; i++) {
            if (isValidBase64Byte(data[i])) {
                temp[bytesCopied++] = data[i];
            }
        }
        byte[] newData = new byte[bytesCopied];
        System.arraycopy(temp, 0, newData, 0, bytesCopied);
        return newData;
    }
    private static String discardNonBase64Chars(String data) {
        StringBuffer sb = new StringBuffer();
        int length = data.length();
        for (int i = 0; i < length; i++) {
            if (isValidBase64Byte((byte) (data.charAt(i)))) {
                sb.append(data.charAt(i));
            }
        }
        return sb.toString();
    }
    private static boolean isValidBase64Byte(byte b) {
        if (b == '=') {
            return true;
        } else if ((b < 0) || (b >= 128)) {
            return false;
        } else if (decodingTable[b] == -1) {
            return false;
        }
        return true;
    }
}

 
array.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<!-- 修改头像 -->
	<string-array name="insert_picture">
		<item>@string/str_take_picture</item>
		<item>@string/str_local_picture</item>
	</string-array>
</resources>
 
String.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, TestPicture!</string>
    <string name="app_name">测试图片上传</string>
   	<string name="str_take_picture">拍照上传</string>
	<string name="str_local_picture">本地图片上传</string>
	<string name="str_modify_head_portrait">修改头像</string>
	
	
	
	
</resources>

 main.xml

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    >
<Button  
	android:id="@+id/bnt"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="上传头像"/>
    
	<ImageView 
		android:id="@+id/imageView" 
		android:layout_marginLeft="50dip"
		android:layout_width="200dip" 
		android:layout_height="200dip" 
		/>
</LinearLayout>
 

你可能感兴趣的:(android)