Android 拍照上传及本地上传


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.       
  18.     try {  
  19.         URL url = new URL(RequestURL);  
  20.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  21.         conn.setReadTimeout(TIME_OUT);  
  22.         conn.setConnectTimeout(TIME_OUT);  
  23.         conn.setDoInput(true);  //允许输入流   
  24.         conn.setDoOutput(true); //允许输出流   
  25.         conn.setUseCaches(false);  //不允许使用缓存   
  26.         conn.setRequestMethod("POST");  //请求方式   
  27.         conn.setRequestProperty("Charset", CHARSET);  //设置编码   
  28.         conn.setRequestProperty("connection""keep-alive");     
  29.         conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);   
  30.           
  31.         if(file!=null)  
  32.         {  
  33.             /** 
  34.              * 当文件不为空,把文件包装并且上传 
  35.              */  
  36.             DataOutputStream dos = new DataOutputStream( conn.getOutputStream());  
  37.             StringBuffer sb = new StringBuffer();  
  38.             sb.append(PREFIX);  
  39.             sb.append(BOUNDARY);  
  40.             sb.append(LINE_END);  
  41.             /** 
  42.              * 这里重点注意: 
  43.              * name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件 
  44.              * filename是文件的名字,包含后缀名的   比如:abc.png   
  45.              */  
  46.             sb.append("Content-Disposition: form-data; name=\"fup\"; filename=\""+file.getName()+"\""+LINE_END);   
  47.             sb.append("Content-Type: image/pjpeg; charset="+CHARSET+LINE_END);  
  48.             sb.append(LINE_END);  
  49.             dos.write(sb.toString().getBytes());  
  50.             InputStream is = new FileInputStream(file);  
  51.             byte[] bytes = new byte[1024];  
  52.             int len = 0;  
  53.             while((len=is.read(bytes))!=-1)  
  54.             {  
  55.                 dos.write(bytes, 0, len);  
  56.             }  
  57.             is.close();  
  58.             dos.write(LINE_END.getBytes());  
  59.             byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();  
  60.             dos.write(end_data);  
  61.             dos.flush();  
  62.             /** 
  63.              * 获取响应码  200=成功 
  64.              * 当响应成功,获取响应的流   
  65.              */  
  66.             int res = conn.getResponseCode();    
  67.             Log.i(TAG, "response code:"+res);  
  68.             if(res==200)  
  69.             {  
  70.                 Log.e(TAG, "request success");  
  71.                 InputStream input =  conn.getInputStream();  
  72.                 StringBuffer sb1= new StringBuffer();  
  73.                 int ss ;  
  74.                 while((ss=input.read())!=-1)  
  75.                 {  
  76.                     sb1.append((char)ss);  
  77.                 }  
  78.                 result = sb1.toString();  
  79.                 Log.i(TAG, "result : "+ result);  
  80.             }  
  81.             else{  
  82.                 Log.i(TAG, "request error");  
  83.             }  
  84.         }  
  85.     } catch (MalformedURLException e) {  
  86.         e.printStackTrace();  
  87.     } catch (IOException e) {  
  88.         e.printStackTrace();  
  89.     }  
  90.     return result;  
  91. }  

这个方法需要传递一个由图片的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, nullnull,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.                       
  30.                 } catch (Exception e) {  
  31.                       
  32.                 }  
  33.                 super.onActivityResult(requestCode, resultCode, data);  
  34.             }  

取值,并且将图片填充到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, nullnull,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 / (float200);  
  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.    }  

相关内容