上傳圖片(來源:相機和相冊)

/////////////////////////////////////////////Activity //////////////////////////////////////////////

public class MainActivity extends Activity {

Context context;
private WebView webView;
private File vFile;
// 表單的數據信息
ValueCallback<Uri> mUploadMessage;
// 表單的結果回調
final int REQ_CHOOSER = 0;// 相冊
final int REQ_CAMERA = 1;// 相機
Uri uriImage;
protected String ImageName;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
init();
}


@SuppressLint("SetJavaScriptEnabled")
private void init() {
webView = (WebView) findViewById(R.id.webView);


WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl("http://101.200.142.201");


webView.setWebViewClient(new WebViewClient());


// 主要處理解析,渲染網頁等瀏覽器做的事情
// WebChromeClient是輔助WebView處理Javascript的對話框,網站圖標,網站title,加載進度等
webView.setWebChromeClient(new WebChromeClient() {


@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadFile,
String acceptType, String capture) {


mUploadMessage = uploadFile;
selectImage();
}
});
}


private void selectImage() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setOnCancelListener(new ReOnCancelListener());
final String[] items = { "相冊", "照相機" };
builder.setItems(items, new OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent();
switch (which) {
case 0:// 選擇相冊
// 設置調用系統相冊的意圖(隱式意圖)
intent.setAction(Intent.ACTION_PICK);
intent.setDataAndType(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"image/*");
MainActivity.this.startActivityForResult(intent,
REQ_CHOOSER);
break;


case 1:// 選擇照相機
// 設置圖片的名稱
ImageName = "/" + getStringToday() + ".jpg";


// 設置調用系統攝像頭的意圖(隱式意圖)
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


// 設置照片的輸出路徑和文件名


File file = new File(Environment
.getExternalStorageDirectory(), ImageName);


intent1.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(file));
// 開啓攝像頭
startActivityForResult(intent1, REQ_CAMERA);





break;
}
}
});
builder.setNegativeButton("取消", new OnClickListener() {


@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}


/** 取消監聽 */
private class ReOnCancelListener implements
DialogInterface.OnCancelListener {


@Override
public void onCancel(DialogInterface dialog) {
if (mUploadMessage != null) {
// 返回null
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
}
}
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQ_CHOOSER:// 相冊
if (resultCode == Activity.RESULT_OK) {
if (mUploadMessage == null) {
return;
}
// 裁剪照片的處理結果
String imagePath = getAbsoluteImagePath(data.getData());
// 進行壓縮
Bitmap bitmap = getimage(imagePath);
// 轉換格式:Bitmap到Uri
uriImage = Uri.parse(MediaStore.Images.Media.insertImage(
getContentResolver(), bitmap, null, null));


Uri result = data == null || resultCode != RESULT_OK ? null
: data.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
} else {
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
}
break;


case REQ_CAMERA:// 相機
if (resultCode == Activity.RESULT_OK) {
// 設置文件保存路徑這裏放在跟目錄下
File picture = new File(Environment
.getExternalStorageDirectory() + ImageName);
//把圖片轉成Bitmap
Bitmap bitmap1 = getimage(picture.getPath());
//把bitmap轉成Uri
Uri imageUri = Uri.parse(MediaStore.Images.Media
.insertImage(getContentResolver(), bitmap1, null,
null));
mUploadMessage.onReceiveValue(imageUri);
mUploadMessage = null;
} else {
mUploadMessage.onReceiveValue(null);
mUploadMessage = null;
}
break;
}
}


/** 獲得圖片絕對路徑 */
protected String getAbsoluteImagePath(Uri uri) {
// can post image
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)


int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();


return cursor.getString(column_index);
}


// http://blog.csdn.net/cherry609195946/article/details/9264409
// android圖片壓縮總結
// // 圖片按比例大小壓縮方法(根據Bitmap圖片壓縮)
// 壓縮圖片url
private Bitmap getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 開始讀入圖片,此時把options.inJustDecodeBounds 設回true了
newOpts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此時返回bm爲空


newOpts.inJustDecodeBounds = false;
int w = newOpts.outWidth;
int h = newOpts.outHeight;
// 現在主流手機比較多是800*480分辨率,所以高和寬我們設置爲
float hh = 800f;// 這裏設置高度爲800f
float ww = 480f;// 這裏設置寬度爲480f
// 縮放比。由於是固定比例縮放,只用高或者寬其中一個數據進行計算即可
int be = 1;// be=1表示不縮放
if (w > h && w > ww) {// 如果寬度大的話根據寬度固定大小縮放
be = (int) (newOpts.outWidth / ww);
} else if (w < h && h > hh) {// 如果高度高的話根據寬度固定大小縮放
be = (int) (newOpts.outHeight / hh);
}
if (be <= 0)
be = 1;
newOpts.inSampleSize = be;// 設置縮放比例
// 重新讀入圖片,注意此時已經把options.inJustDecodeBounds 設回false了
bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compressImage(bitmap);// 壓縮好比例大小後再進行質量壓縮
}


/** 壓縮圖片 */
private Bitmap compressImage(Bitmap image) {


ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 質量壓縮方法,這裏100表示不壓縮,把壓縮後的數據存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > 100) { // 循環判斷如果壓縮後圖片是否大於100kb,大於繼續壓縮
baos.reset();// 重置baos即清空baos
image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這裏壓縮options%,把壓縮後的數據存放到baos中
options -= 10;// 每次都減少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮後的數據baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream數據生成圖片
return bitmap;
}

public static String getStringToday() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = formatter.format(currentTime);
return dateString;
}

}

/////////////////////////////////////////////activity_main //////////////////////////////////////////////

<RelativeLayout 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"
    tools:context=".MainActivity" >


    <WebView 
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />


</RelativeLayout>

/////////////////////////////////////////////權限 //////////////////////////////////////////////

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章