android拍照上传
16lz
2021-01-23
文章转账:http://blog.csdn.net/lb454048898/article/details/7672198
首先是上传的 PostFile
[java] view plain copy- //上传代码,第一个参数,为要使用的URL,第二个参数,为表单内容,第三个参数为要上传的文件,可以上传多个文件,这根据需要页定
- privatestaticfinalStringTAG="uploadFile";
- privatestaticfinalintTIME_OUT=10*1000;//超时时间
- privatestaticfinalStringCHARSET="utf-8";//设置编码
- /**
- *android上传文件到服务器
- *@paramfile需要上传的文件
- *@paramRequestURL请求的rul
- *@return返回响应的内容
- */
- publicstaticStringuploadFile(Filefile,StringRequestURL)
- {
- Stringresult=null;
- StringBOUNDARY=UUID.randomUUID().toString();//边界标识随机生成
- StringPREFIX="--",LINE_END="\r\n";
- StringCONTENT_TYPE="multipart/form-data";//内容类型
- try{
- URLurl=newURL(RequestURL);
- HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
- conn.setReadTimeout(TIME_OUT);
- conn.setConnectTimeout(TIME_OUT);
- conn.setDoInput(true);//允许输入流
- conn.setDoOutput(true);//允许输出流
- conn.setUseCaches(false);//不允许使用缓存
- conn.setRequestMethod("POST");//请求方式
- conn.setRequestProperty("Charset",CHARSET);//设置编码
- conn.setRequestProperty("connection","keep-alive");
- conn.setRequestProperty("Content-Type",CONTENT_TYPE+";boundary="+BOUNDARY);
- if(file!=null)
- {
- /**
- *当文件不为空,把文件包装并且上传
- */
- DataOutputStreamdos=newDataOutputStream(conn.getOutputStream());
- StringBuffersb=newStringBuffer();
- sb.append(PREFIX);
- sb.append(BOUNDARY);
- sb.append(LINE_END);
- /**
- *这里重点注意:
- *name里面的值为服务器端需要key只有这个key才可以得到对应的文件
- *filename是文件的名字,包含后缀名的比如:abc.png
- */
- sb.append("Content-Disposition:form-data;name=\"fup\";filename=\""+file.getName()+"\""+LINE_END);
- sb.append("Content-Type:image/pjpeg;charset="+CHARSET+LINE_END);
- sb.append(LINE_END);
- dos.write(sb.toString().getBytes());
- InputStreamis=newFileInputStream(file);
- byte[]bytes=newbyte[1024];
- intlen=0;
- while((len=is.read(bytes))!=-1)
- {
- dos.write(bytes,0,len);
- }
- is.close();
- dos.write(LINE_END.getBytes());
- byte[]end_data=(PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
- dos.write(end_data);
- dos.flush();
- /**
- *获取响应码200=成功
- *当响应成功,获取响应的流
- */
- intres=conn.getResponseCode();
- Log.i(TAG,"responsecode:"+res);
- if(res==200)
- {
- Log.e(TAG,"requestsuccess");
- InputStreaminput=conn.getInputStream();
- StringBuffersb1=newStringBuffer();
- intss;
- while((ss=input.read())!=-1)
- {
- sb1.append((char)ss);
- }
- result=sb1.toString();
- Log.i(TAG,"result:"+result);
- }
- else{
- Log.i(TAG,"requesterror");
- }
- }
- }catch(MalformedURLExceptione){
- e.printStackTrace();
- }catch(IOExceptione){
- e.printStackTrace();
- }
- returnresult;
- }
这个方法需要传递一个由图片的path(路径)生成的file格式的数据。和上传地址的url。
首先是本地上传。
[java] view plain copy- /***
- *这个是调用android内置的intent,来过滤图片文件,同时也可以过滤其他的
- */
- Intentintent=newIntent();
- intent.setType("image/*");
- intent.setAction(Intent.ACTION_GET_CONTENT);
- startActivityForResult(intent,selectCode);
这个是调用本地图片库。
返回过后是在 ResultActivty里返回。
[java] view plain copy- protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
- super.onActivityResult(requestCode,resultCode,data);
- if(selectCode==requestCode){
- /**
- *当选择的图片不为空的话,在获取到图片的途径
- */
- Uriuri=data.getData();
- Log.i(TAG,"uri="+uri);
- try{
- String[]pojo={MediaStore.Images.Media.DATA};
- Cursorcursor=managedQuery(uri,pojo,null,null,null);
- if(cursor!=null)
- {
- ContentResolvercr=this.getContentResolver();
- intcolunm_index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
- cursor.moveToFirst();
- Stringpath=cursor.getString(colunm_index);
- /***
- *这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了,这样的话,我们判断文件的后缀名
- *如果是图片格式的话,那么才可以
- */
- if(path.endsWith("jpg")||path.endsWith("png"))
- {
- picPath=path;
- Bitmapbitmap=BitmapFactory.decodeStream(cr.openInputStream(uri));
- imageView.setImageBitmap(bitmap);
- }else{alert();}
- }else{alert();}
- }catch(Exceptione){
- }
- super.onActivityResult(requestCode,resultCode,data);
- }
取值,并且将图片填充到imageView里。本Activty里全局变量保存picPath。
拍照上传,首先要进入照相机。
[java] view plain copy- destoryBimap();
- Stringstate=Environment.getExternalStorageState();
- if(state.equals(Environment.MEDIA_MOUNTED)){
- intent=newIntent("android.media.action.IMAGE_CAPTURE");
- startActivityForResult(intent,cameraCode);
- }else{
- Toast.makeText(SsActivity.this,"请插入SD卡",Toast.LENGTH_LONG).show();
- }
- break;
判断有没有SD卡。没有就提示插入SD卡。接受返回值任然实在ResultActivity
[java] view plain copy- if(cameraCode==requestCode){
- Bundlebundle=data.getExtras();
- photo=(Bitmap)bundle.get("data");//获取相机返回的数据,并转换为Bitmap图片格式
- ByteArrayOutputStreambaos=newByteArrayOutputStream();
- photo.compress(Bitmap.CompressFormat.JPEG,100,baos);//把数据写入文件
- Uriuri=data.getData();
- Log.i(TAG,"uri="+uri);
- try{
- String[]pojo={MediaStore.Images.Media.DATA};
- Cursorcursor=managedQuery(uri,pojo,null,null,null);
- if(cursor!=null){
- intcolunm_index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
- cursor.moveToFirst();
- Stringpath=cursor.getString(colunm_index);
- if(path!=null){
- picPath=path;
- imageView.setImageBitmap(photo);
- }
- }
- }catch(Exceptione){
- //TODO:handleexception
- }
- }
此返回值跟上面本地取图片一样。返回picPath,并且将图片填充至imageView。
上传:
[java] view plain copy- Filefile=newFile(saveBefore(picPath));
- if(file!=null)
- {
- Stringrequest=PostFile.uploadFile(file,requestURL);
- uploadImage.setText(request);
- }
- break;
上传之前将图片压缩。
现在附上一些转换方法
[java] view plain copy- privatevoiddestoryBimap(){
- if(photo!=null&&!photo.isRecycled()){
- photo.recycle();
- photo=null;
- }
- }
- /**
- *读取路径中的图片,然后将其转化为缩放后的bitmap
- *@parampath
- */
- publicStringsaveBefore(Stringpath){
- BitmapFactory.Optionsoptions=newBitmapFactory.Options();
- options.inJustDecodeBounds=true;
- //获取这个图片的宽和高
- Bitmapbitmap=BitmapFactory.decodeFile(path,options);//此时返回bm为空
- options.inJustDecodeBounds=false;
- //计算缩放比
- intbe=(int)(options.outHeight/(float)200);
- if(be<=0)
- be=1;
- options.inSampleSize=4;//图片长宽各缩小至四分之一
- //重新读入图片,注意这次要把options.inJustDecodeBounds设为false哦
- bitmap=BitmapFactory.decodeFile(path,options);
- //savePNG_After(bitmap,path);
- returnsaveJPGE_After(bitmap,path);
- }
- /**
- *保存图片为JPEG
- *@parambitmap
- *@parampath
- */
- publicStringsaveJPGE_After(Bitmapbitmap,Stringpath){
- Filefile=newFile(path);
- try{
- FileOutputStreamout=newFileOutputStream(file);
- if(bitmap.compress(Bitmap.CompressFormat.JPEG,100,out)){
- out.flush();
- out.close();
- }
- }catch(FileNotFoundExceptione){
- e.printStackTrace();
- }catch(IOExceptione){
- e.printStackTrace();
- }
- returnpath;
- }
更多相关文章
- Android 导入android源码有错,R.java文件不能自动生成解决方法
- Android 控件之Gallery和ImageSwitcher图片切换器
- Android dex ,xml 文件反编译方法
- android/java 计算大文件的sha1值
- android中使用Thumbnails批量加载sdcard中的缩略图片