/**
* 拍照
*/
private void takePicture() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
String[] strs = { "拍照上传", "相册选取" };
builder.setItems(strs, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
// Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Intent camera = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(camera, 1);
break;
case 1:
Intent picture = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(picture, 2);
break;
}
}
});
builder.create().show();
}
// 保存图片
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("1", "data---->" + data);
if (requestCode == 1 && data != null && resultCode == Activity.RESULT_OK) {
// 直接获取照片
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
if (bitmap != null) {
m_chezhaopian.setVisibility(View.VISIBLE);
m_chezhaopian.setImageBitmap(bitmap);
}
//保存图片
try {
File outDir = null;
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
//判断状态,保存到sd卡中公有目录(根目录)的pictures文件夹下
outDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
}
else {
if (getActivity() != null) {
//保存安装包下的文件夹中
outDir = getActivity().getFilesDir();
}
}
if (!outDir.exists()) {
outDir.mkdirs();
}
outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
FileOutputStream fos = new FileOutputStream(outFile);
boolean flag = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);// 把数据写入文件
Log.i("1", "flag=" + flag);
if (flag) {
TUtil.s("图片已保存至:" + outFile.getAbsolutePath());
// submitData();
// setDialog();
} else {
TUtil.s("图片保存失败!");
}
} catch (FileNotFoundException e) {
Log.e("1", e.getMessage());
}
} else if (requestCode == 1 && data == null && resultCode == Activity.RESULT_OK) {
m_btn_querentingche.setEnabled(true);
if (getActivity() != null) {
m_btn_querentingche.setBackgroundColor(getActivity().getResources().getColor(
R.color.background_huangse));
}
}
// 相册显示界面
else if (requestCode == 2 && data != null && resultCode == Activity.RESULT_OK) {
try {
Uri selectedImage = data.getData();
String[] filePathColumns = { MediaStore.Images.Media.DATA };
Cursor c = getActivity().getContentResolver().query(selectedImage, filePathColumns,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePathColumns[0]);
picturePath = c.getString(columnIndex);
c.close();
//调用压缩方法压缩图片
// Bitmap bitmap = createThumbnail(picturePath, 10);
// m_chezhaopian.setImageBitmap(bitmap);
// outFile = new File(picturePath);
// picFileFullName2 = outFile.getAbsoluteFile();
// FileOutputStream fos = new FileOutputStream(outFile);
// if (bitmap != null) {
// m_chezhaopian.setVisibility(View.VISIBLE);
// m_chezhaopian.setImageBitmap(bitmap);
//
// }
//
// boolean flag = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);// 把数据写入文件
outFile = new File(picturePath);
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
if (bitmap != null) {
m_chezhaopian.setVisibility(View.VISIBLE);
m_chezhaopian.setImageBitmap(bitmap);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
}
//采样对图片进行压缩
// private Bitmap createThumbnail(String filepath, int sampleSize) {
//BitmapFactory.Options options = new BitmapFactory.Options();
// 缩放比例(取值大的)
//options.inSampleSize = sampleSize;
//return BitmapFactory.decodeFile(filepath, options);
//
//上传照片
public void submitData(File outFile) {
new myTask(outFile).execute();
}
private ProgressDialog imgProgress;
class myTask extends AsyncTask {
private File file;
public myTask(File file) {
this.file = file;
}
@Override
protected void onPreExecute() {
imgProgress = new ProgressDialog(getActivity());
DialogUtil.showProgress(imgProgress, "图片上传中...");
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... param) {
Map params = new HashMap();
// params.put("taskid", data.getId()+"");
params.put("orderNo", data.getVorderNo());// 单号
// params.put("autoNo", "");//车牌号
params.put("autoNo", et.getText().toString());// 车牌号
SUtil sUtil = new SUtil();
params.put("token", sUtil.getToken(getActivity()));// token
String str;
try {
// 路径,调用上传图片的工具类
str = UploadFileUtil.uploadSubmit(getActivity(), RequestUrl.upload, params, file);// outFile
DialogUtil.dismissProgress(imgProgress);
Log.i("1", "JieCheBFragment---》str:" + str);
if (str != null) {
Gson gson = new Gson();
StringEntity entity = gson.fromJson(str, StringEntity.class);
Log.i("1", "JieCheBFragment---》Status:" + entity.getStatus());
if (entity.getStatus() == 0) {
onSwitchlistener.doSwitch(3);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
//真正上传图片的工具类
public static String uploadSubmit(Context context, String url, Map param,
File file) throws Exception {
HttpPost post = new HttpPost(url);
/**
* 注意这里如果只用new MultipartEntity()无参的构造方法,则传过去的中文是乱码
*/
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
Charset.forName("UTF-8"));
if (param != null && !param.isEmpty()) {
for (Map.Entry entry : param.entrySet()) {
entity.addPart(entry.getKey(),
new StringBody(entry.getValue(), Charset.forName("UTF-8")));
}
}
// 添加文件参数
if (file != null && file.exists()) {
entity.addPart("file", new FileBody(file));
}
post.setEntity(entity);
HttpResponse response = HttpClient.getHttpClient(context).execute(post);
int stateCode = response.getStatusLine().getStatusCode();
StringBuffer sb = new StringBuffer();
if (stateCode == HttpStatus.SC_OK) {
HttpEntity result = response.getEntity();
if (result != null) {
InputStream is = result.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String tempLine;
while ((tempLine = br.readLine()) != null) {
sb.append(tempLine);
}
}
}
post.abort();
return sb.toString();
}
}
最后一定记着,在发http请求的时候要记着导架包 httpmime-4.2.2.jar
我的相关博客