从相册获取图片及调用相机拍照获取图片,最后上传图片到服务器

时间:2022-09-18 23:02:34
调用相机拍照获取图片: 跳转到到拍照界面:   Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //下面这句指定调用相机拍照后的照片存储的路径 mSzImageFileName = Long.toString(System.currentTimeMillis()) + ".png"; takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), mSzImageFileName))); startActivityForResult(takeIntent, REQUEST_TAKE_PHOTO);   从相册获取图片:  从相册选择图片:   Intent pickIntent = new Intent(Intent.ACTION_PICK, null); // 如果要限制上传到服务器的图片类型时可以直接写如:image/jpeg 、 image/png等的类型 pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(pickIntent, REQUEST_PICK_PHOTO);    从相册返回一张图片或者拍照返回一张图片: 监听返回结果: @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_PICK_PHOTO:// 直接从相册获取 try { startPhotoZoom(data.getData());//跳转到截图界面 } catch (NullPointerException e) { e.printStackTrace();// 用户点击取消操作 } break; case REQUEST_TAKE_PHOTO:// 调用相机拍照 mHandler.postDelayed(new Runnable() { @Override public void run() { File temp = new File(Environment.getExternalStorageDirectory(), mSzImageFileName); if (temp.exists()) { startPhotoZoom(Uri.fromFile(temp));//跳转到截图界面 } } }, 1000); break; case REQUEST_CUT_PHOTO:// 取得裁剪后的图片 if (data != null) { setPicToView(data);//保存和上传图片 } break; }   super.onActivityResult(requestCode, resultCode, data); }   返回图片后进行裁剪: 裁剪图片: /** * 裁剪图片方法实现 */ private void startPhotoZoom(Uri uri) { LogUtil.e("PersonalInformationActivity", "onActivityResult uri" + uri); if (uri != null) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪 intent.putExtra("crop", "true"); // aspectX aspectY 是宽高的比例 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX outputY 是裁剪图片宽高 intent.putExtra("outputX", 300); intent.putExtra("outputY", 300); intent.putExtra("return-data", true); startActivityForResult(intent, REQUEST_CUT_PHOTO); } }   裁剪后保存和上传图片: /** * 保存裁剪之后的图片数据 * * @param picdata */ private void setPicToView(Intent picdata) { Bundle extras = picdata.getExtras(); if (extras != null) { // 取得SDCard图片路径做显示 Bitmap photo = extras.getParcelable("data"); mSzImageFileName = Long.toString(System.currentTimeMillis()) + ".png"; mImgUrlPath = Environment.getExternalStorageDirectory() + File.separator + "cut_image" + File.separator + mSzImageFileName; try { NetUtil.saveBitmapToFile(photo, mImgUrlPath); } catch (IOException e) { e.printStackTrace(); }     // 新线程后台上传服务端 new Thread(uploadImageRunnable).start(); } }   上传图片的线程: Runnable uploadImageRunnable = new Runnable() { @Override public void run() { Map<String, String> params = new HashMap<>(); params.put("mid", mSzId);//上传参数 Map<String, File> files = new HashMap<>(); files.put("myUpload", new File(mImgUrlPath));//上传文件路径 try { String json = NetUtil.uploadFile(Constants.URL_EDIT_IMG, params, files); //json为服务器返回的数据,可自己解析(如json解析)取得想要的数据 } } } catch (IOException e) { e.printStackTrace(); } } };   保存图片和上传图片的工具类NetUtil : public class NetUtil {//上传图片到服务器public static String uploadFile(String url, Map<String, String> params, Map<String, File> files)throws IOException {String tempStr = null;String BOUNDARY = java.util.UUID.randomUUID().toString();String PREFIX = "--", LINEND = "\r\n";String MULTIPART_FROM_DATA = "multipart/form-data";String CHARSET = "UTF-8";HttpURLConnection conn = null;try {URL uri = new URL(url);conn = (HttpURLConnection) uri.openConnection();conn.setReadTimeout(10 * 1000); // 缓存的最长时间conn.setDoInput(true);// 允许输入conn.setDoOutput(true);// 允许输出conn.setUseCaches(false); // 不允许使用缓存conn.setRequestMethod("POST");conn.setRequestProperty("connection", "keep-alive");conn.setRequestProperty("Charsert", "UTF-8");conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);// 首先组拼文本类型的参数StringBuilder sb = new StringBuilder();for (Map.Entry<String, String> entry : params.entrySet()) {sb.append(PREFIX);sb.append(BOUNDARY);sb.append(LINEND);sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);sb.append("Content-Transfer-Encoding: 8bit" + LINEND);sb.append(LINEND);sb.append(entry.getValue());sb.append(LINEND);}LogUtil.e("NetUtil", "uploadFile sb:" + sb.toString());DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());outStream.write(sb.toString().getBytes());// 发送文件数据if (files != null)for (Map.Entry<String, File> file : files.entrySet()) {StringBuilder sb1 = new StringBuilder();sb1.append(PREFIX);sb1.append(BOUNDARY);sb1.append(LINEND);sb1.append("Content-Disposition: form-data; name="+file.getKey()+"; filename=\""+ file.getValue() + "\"" + LINEND);sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);sb1.append(LINEND);LogUtil.e("NetUtil", "uploadFile sb1:" + sb1.toString());outStream.write(sb1.toString().getBytes());InputStream is = new FileInputStream(file.getValue());byte[] buffer = new byte[1024];int len = 0;while ((len = is.read(buffer)) != -1) {outStream.write(buffer, 0, len);}is.close();outStream.write(LINEND.getBytes());}// 请求结束标志byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();outStream.write(end_data);outStream.flush();outStream.close();StringBuilder sb2 = new StringBuilder();BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), CHARSET));String inputLine;while ((inputLine = in.readLine()) != null) {sb2.append(inputLine);}in.close();tempStr = sb2.toString();} catch (Exception e) {} finally {if (conn != null) {conn.disconnect();}}return tempStr;} /*** Save Bitmap to a file.保存图片到SD卡。** @param bitmap* @return error message if the saving is failed. null if the saving is* successful.* @throws IOException*/public static void saveBitmapToFile(Bitmap bitmap, String _file)throws IOException {BufferedOutputStream os = null;try {File file = new File(_file);int end = _file.lastIndexOf(File.separator);String _filePath = _file.substring(0, end);File filePath = new File(_filePath);if (!filePath.exists()) {filePath.mkdirs();}file.createNewFile();os = new BufferedOutputStream(new FileOutputStream(file));bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);} finally {if (os != null) {try {os.close();} catch (IOException e) {}}}}}