歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 拍照上傳及本地上傳

Android 拍照上傳及本地上傳

日期:2017/3/1 10:18:47   编辑:Linux編程

Android 拍照上傳及本地上傳:

首先是上傳的 PostFile

  1. //上傳代碼,第一個參數,為要使用的URL,第二個參數,為表單內容,第三個參數為要上傳的文件,可以上傳多個文件,這根據需要頁定
  2. private static final String TAG = "uploadFile";
  3. private static final int TIME_OUT = 10*1000; //超時時間
  4. private static final String CHARSET = "utf-8"; //設置編碼
  5. /**
  6. * android上傳文件到服務器
  7. * @param file 需要上傳的文件
  8. * @param RequestURL 請求的rul
  9. * @return 返回響應的內容
  10. */
  11. public static String uploadFile(File file,String RequestURL)
  12. {
  13. String result = null;
  14. String BOUNDARY = UUID.randomUUID().toString(); //邊界標識 隨機生成
  15. String PREFIX = "--" , LINE_END = "\r\n";
  16. String CONTENT_TYPE = "multipart/form-data"; //內容類型
  17. try {
  18. URL url = new URL(RequestURL);
  19. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  20. conn.setReadTimeout(TIME_OUT);
  21. conn.setConnectTimeout(TIME_OUT);
  22. conn.setDoInput(true); //允許輸入流
  23. conn.setDoOutput(true); //允許輸出流
  24. conn.setUseCaches(false); //不允許使用緩存
  25. conn.setRequestMethod("POST"); //請求方式
  26. conn.setRequestProperty("Charset", CHARSET); //設置編碼
  27. conn.setRequestProperty("connection", "keep-alive");
  28. conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
  29. if(file!=null)
  30. {
  31. /**
  32. * 當文件不為空,把文件包裝並且上傳
  33. */
  34. DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
  35. StringBuffer sb = new StringBuffer();
  36. sb.append(PREFIX);
  37. sb.append(BOUNDARY);
  38. sb.append(LINE_END);
  39. /**
  40. * 這裡重點注意:
  41. * name裡面的值為服務器端需要key 只有這個key 才可以得到對應的文件
  42. * filename是文件的名字,包含後綴名的 比如:abc.png
  43. */
  44. sb.append("Content-Disposition: form-data; name=\"fup\"; filename=\""+file.getName()+"\""+LINE_END);
  45. sb.append("Content-Type: image/pjpeg; charset="+CHARSET+LINE_END);
  46. sb.append(LINE_END);
  47. dos.write(sb.toString().getBytes());
  48. InputStream is = new FileInputStream(file);
  49. byte[] bytes = new byte[1024];
  50. int len = 0;
  51. while((len=is.read(bytes))!=-1)
  52. {
  53. dos.write(bytes, 0, len);
  54. }
  55. is.close();
  56. dos.write(LINE_END.getBytes());
  57. byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
  58. dos.write(end_data);
  59. dos.flush();
  60. /**
  61. * 獲取響應碼 200=成功
  62. * 當響應成功,獲取響應的流
  63. */
  64. int res = conn.getResponseCode();
  65. Log.i(TAG, "response code:"+res);
  66. if(res==200)
  67. {
  68. Log.e(TAG, "request success");
  69. InputStream input = conn.getInputStream();
  70. StringBuffer sb1= new StringBuffer();
  71. int ss ;
  72. while((ss=input.read())!=-1)
  73. {
  74. sb1.append((char)ss);
  75. }
  76. result = sb1.toString();
  77. Log.i(TAG, "result : "+ result);
  78. }
  79. else{
  80. Log.i(TAG, "request error");
  81. }
  82. }
  83. } catch (MalformedURLException e) {
  84. e.printStackTrace();
  85. } catch (IOException e) {
  86. e.printStackTrace();
  87. }
  88. return result;
  89. }

這個方法需要傳遞一個由圖片的path(路徑)生成的file格式的數據。和上傳地址的url。

首先是本地上傳。

  1. /***
  2. * 這個是調用android內置的intent,來過濾圖片文件 ,同時也可以過濾其他的
  3. */
  4. Intent intent = new Intent();
  5. intent.setType("image/*");
  6. intent.setAction(Intent.ACTION_GET_CONTENT);
  7. startActivityForResult(intent, selectCode);

這個是調用本地圖片庫。

返回過後是在 ResultActivty裡返回。

  1. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  2. super.onActivityResult(requestCode, resultCode, data);
  3. if(selectCode==requestCode){
  4. /**
  5. * 當選擇的圖片不為空的話,在獲取到圖片的途徑
  6. */
  7. Uri uri = data.getData();
  8. Log.i(TAG, "uri = "+ uri);
  9. try {
  10. String[] pojo = {MediaStore.Images.Media.DATA};
  11. Cursor cursor = managedQuery(uri, pojo, null, null,null);
  12. if(cursor!=null)
  13. {
  14. ContentResolver cr = this.getContentResolver();
  15. int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  16. cursor.moveToFirst();
  17. String path = cursor.getString(colunm_index);
  18. /***
  19. * 這裡加這樣一個判斷主要是為了第三方的軟件選擇,比如:使用第三方的文件管理器的話,你選擇的文件就不一定是圖片了,這樣的話,我們判斷文件的後綴名
  20. * 如果是圖片格式的話,那麼才可以
  21. */
  22. if(path.endsWith("jpg")||path.endsWith("png"))
  23. {
  24. picPath = path;
  25. Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
  26. imageView.setImageBitmap(bitmap);
  27. }else{alert();}
  28. }else{alert();}
  29. } catch (Exception e) {
  30. }
  31. super.onActivityResult(requestCode, resultCode, data);
  32. }

取值,並且將圖片填充到imageView裡。本Activty裡全局變量保存picPath。

拍照上傳,首先要進入照相機。

  1. destoryBimap();
  2. String state = Environment.getExternalStorageState();
  3. if (state.equals(Environment.MEDIA_MOUNTED)) {
  4. intent = new Intent("android.media.action.IMAGE_CAPTURE");
  5. startActivityForResult(intent, cameraCode);
  6. } else {
  7. Toast.makeText(SsActivity.this,"請插入SD卡", Toast.LENGTH_LONG).show();
  8. }
  9. break;

判斷有沒有SD卡。沒有就提示插入SD卡。接受返回值任然實在ResultActivity

  1. if(cameraCode==requestCode){
  2. Bundle bundle = data.getExtras();
  3. photo= (Bitmap) bundle.get("data");// 獲取相機返回的數據,並轉換為Bitmap圖片格式
  4. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  5. photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 把數據寫入文件
  6. Uri uri = data.getData();
  7. Log.i(TAG, "uri = "+ uri);
  8. try {
  9. String[] pojo = {MediaStore.Images.Media.DATA};
  10. Cursor cursor = managedQuery(uri, pojo, null, null,null);
  11. if(cursor!=null){
  12. int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  13. cursor.moveToFirst();
  14. String path = cursor.getString(colunm_index);
  15. if(path!=null){
  16. picPath=path;
  17. imageView.setImageBitmap(photo);
  18. }
  19. }
  20. }catch (Exception e) {
  21. // TODO: handle exception
  22. }
  23. }

此返回值跟上面本地取圖片一樣。返回picPath,並且將圖片填充至imageView。

上傳:

  1. File file = new File(saveBefore(picPath));
  2. if(file!=null)
  3. {
  4. String request = PostFile.uploadFile( file, requestURL);
  5. uploadImage.setText(request);
  6. }
  7. break;

上傳之前將圖片壓縮。

現在附上一些轉換方法

  1. private void destoryBimap() {
  2. if (photo != null && !photo.isRecycled()) {
  3. photo.recycle();
  4. photo = null;
  5. }
  6. }

  1. /**
  2. * 讀取路徑中的圖片,然後將其轉化為縮放後的bitmap
  3. * @param path
  4. */
  5. public String saveBefore(String path) {
  6. BitmapFactory.Options options = new BitmapFactory.Options();
  7. options.inJustDecodeBounds = true;
  8. // 獲取這個圖片的寬和高
  9. Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此時返回bm為空
  10. options.inJustDecodeBounds = false;
  11. // 計算縮放比
  12. int be = (int) (options.outHeight / (float) 200);
  13. if (be <= 0)
  14. be = 1;
  15. options.inSampleSize = 4; // 圖片長寬各縮小至四分之一
  16. // 重新讀入圖片,注意這次要把options.inJustDecodeBounds 設為 false哦
  17. bitmap = BitmapFactory.decodeFile(path, options);
  18. // savePNG_After(bitmap,path);
  19. return saveJPGE_After(bitmap, path);
  20. }
  21. /**
  22. * 保存圖片為JPEG
  23. * @param bitmap
  24. * @param path
  25. */
  26. public String saveJPGE_After(Bitmap bitmap, String path) {
  27. File file = new File(path);
  28. try {
  29. FileOutputStream out = new FileOutputStream(file);
  30. if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
  31. out.flush();
  32. out.close();
  33. }
  34. } catch (FileNotFoundException e) {
  35. e.printStackTrace();
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }
  39. return path;
  40. }
Copyright © Linux教程網 All Rights Reserved