上传图片(来源:相机和相册)

/////////////////////////////////////////////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"/>

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