一.拍照 發起拍照動作
public void photo() {
try{
Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
openCameraIntent.putExtra(MediaStore. EXTRA_OUTPUT, Uri.fromFile( new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
startActivityForResult(openCameraIntent, TAKE_PICTURE);
} catch (Exception e){
Log. e(TAG,e.getMessage());
}
}
拍完照片的回調方法邏輯
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
switch (requestCode) {
case TAKE_PICTURE :
if (Bimp.tempSelectBitmap .size() < 9 && resultCode == RESULT_OK) {
//將保存在本地的圖片取出並縮小後顯示在界面上
String aa = Environment.getExternalStorageDirectory()+ "/temp.jpg";
Log.e(TAG,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA:"+aa);
Bitmap camorabitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/temp.jpg");
if(null != camorabitmap ){
// 下面這兩句是對圖片按照一定的比例縮放,這樣就可以完美地顯示出來。
int scale = Bimp.reckonThumbnail(camorabitmap.getWidth(),camorabitmap.getHeight(), 500, 600);
Bitmap bitMap = Bimp. PicZoom(camorabitmap, camorabitmap.getWidth() / scale,camorabitmap.getHeight() / scale);
//由於Bitmap內存佔用較大,這裏需要回收內存,否則會報out of memory異常
camorabitmap.recycle();
camorabitmap= null;
String timestamp = Integer.toString((int)(System. currentTimeMillis() / 1000));
File tempFile = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
File saveFile = new File(Environment.getExternalStorageDirectory(), timestamp+ ".jpg");
tempFile.renameTo(saveFile);
String filePath = timestamp+ ".jpg";
ImageItem takePhoto = new ImageItem();
takePhoto.setImagePath(filePath);
takePhoto.setBitmap(bitMap);
Bimp. tempSelectBitmap.add(takePhoto);
adapter.notifyDataSetChanged();
}
}
break;
case DEL_PICTURE :
if(resultCode == 1){
adapter.notifyDataSetChanged();
}
break;
}
}
1.其中主要是按照壓縮的尺寸計算出壓縮的比例,然後進行壓縮得到壓縮後的圖片數據
int scale = Bimp.reckonThumbnail(camorabitmap.getWidth(),camorabitmap.getHeight(), 500, 600);
Bitmap bitMap = Bimp. PicZoom(camorabitmap, camorabitmap.getWidth() / scale,camorabitmap.getHeight() / scale);
//計算需要壓縮的比例
public static int reckonThumbnail (int oldWidth, int oldHeight, int newWidth, int newHeight) {
if ((oldHeight > newHeight && oldWidth > newWidth)
|| (oldHeight <= newHeight && oldWidth > newWidth)) {
int be = (int ) (oldWidth / (float) newWidth);
if (be <= 1)
be = 1;
return be;
} else if (oldHeight > newHeight && oldWidth <= newWidth) {
int be = (int ) (oldHeight / (float) newHeight);
if (be <= 1)
be = 1;
return be;
}
return 1;
}
//根據比例壓縮得到壓縮的數據
public static Bitmap PicZoom(Bitmap bmp, int width, int height) {
int bmpWidth = bmp.getWidth();
int bmpHeght = bmp.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(( float) width / bmpWidth, (float) height / bmpHeght);
return Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeght, matrix, true);
}
二.從相冊中選取
private void choosePhoto () {
// Intent intent = new Intent(Intent.ACTION_PICK);
// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media. EXTERNAL_CONTENT_URI);
intent.setType( "image/*");// 相片類型
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
}
case REQUEST_CODE_PICK_IMAGE :
if(resultCode == Activity.RESULT_OK) {
Uri imageUri = data.getData();
if(null != imageUri && !"".equals(imageUri)){
Photo photo = new Photo();
ContentResolver cr = this.getContentResolver();
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA };
Cursor cursor =
getContentResolver().query(imageUri,filePathColumn, null, null,
null);
cursor.moveToFirst(); //將遊標移到第一位
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);//獲取圖片路徑
photo.setType(2); //來源sd卡
photo.setPath(imagePath);
LXLog. i("相冊", imagePath);
imageGrid.setVisibility(View.VISIBLE);
PhotoContext. photos.add(photo);
photoGrid.notifyDataSetChanged();
cursor.close(); //關閉遊標
} catch (Exception e) {
Toast. makeText(getApplicationContext(), "內存溢出" ,
Toast. LENGTH_LONG).show();
e.printStackTrace();
}
}
}
三 上傳附件,選擇文件 onActivityResult 裏面的關鍵代碼
case FILE_SELECT_CODE:
if (data != null) {
Uri uri = data.getData();
String path = URLUtil. getPath(this, uri);
if (!StringUtils.isEmpty(path)) {
progress = new ProgressDialog(EditWorkDiaryActivity.this );
progress.setProgressStyle(ProgressDialog. STYLE_HORIZONTAL);
progress.setMessage( "附件上傳" );
progress.setOnCancelListener( new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
progress.dismiss();
HttpAsyncUtil. cancel(EditWorkDiaryActivity.this,
true);
}
});
progress.setCancelable( true);
progress. setButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
progress.dismiss();
HttpAsyncUtil. cancel(
EditWorkDiaryActivity. this, true);
}
}) ;
progress.show();
uploadAttachment(path);
}
}
break;
URLUtil.getPath(this, uri);
工具方法主要解決個個手機的文件存儲位置不一致問題
package com.shjy.jingin.util;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Map;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
/**
* Created by Administrator on 2015/11/5.
*/
public class URLUtil {
public static void main(String [] args){
String url = "sms:10086?body=%E5%BC%A0%E6%88%90%E9%BE%99%E9%82%80%E8%AF%B7%E6%82%A8%E5%8A%A0%E5%85%A5%E4%B8%8A%E6%B5%B7%E6%96%87%E6%80%9D%E6%B5%B7%E8%BE%89%E9%9B%86%E5%9B%A2,%E8%AF%B7%E7%82%B9%E5%87%BB%E9%93%BE%E6%8E%A5[http://www.jingin.cn/invite.htm?code=Pd9g4l]%E5%AE%8C%E6%88%90%E6%B3%A8%E5%86%8C%EF%BC%8C%E8%AF%A5%E9%93%BE%E6%8E%A524%E5%B0%8F%E6%97%B6%E5%86%85%E6%9C%89%E6%95%88%E3%80%82[%E7%BB%8F%E8%90%A5%E7%AE%A1%E5%AE%B6]";
try {
// Uri uri = Uri.parse(url);
// String body = uri.getQueryParameter("body")==null?"":uri.getQueryParameter("body");
Map map = splitQuery(url);
String body = (String)map.get("body");
System.out.println(body);
}catch (Exception e){
e.printStackTrace();
}
// Map kvMap;
// try {
// kvMap = URLUtil.splitQuery("http://www.phpcode8.com/?p=1451&id=888&xx=yy");
// System.out.println(kvMap.get("id"));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// } catch (MalformedURLException e) {
// e.printStackTrace();
// }
}
public static Map splitQuery(String url) throws UnsupportedEncodingException {
Map query_pairs = new LinkedHashMap();
int beginIndex = url.indexOf("?")==-1?0:url.indexOf("?")+1;
String query = url.substring(beginIndex);
String[] pairs = query.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
}
return query_pairs;
}
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
*/
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}
----
spring mvc+tomcat源碼分析視頻(鏈接複製在瀏覽器打開)
https://study.163.com/course/courseMain.htm?share=2&shareId=480000001919582&courseId=1209399899&_trace_c_p_k2_=6d81bc445e9c462ab8d6345e40f6b0bf