文章转账:http://blog.csdn.net/lb454048898/article/details/7672198

首先是上传的 PostFile

[java] view plain copy
  1. //上传代码,第一个参数,为要使用的URL,第二个参数,为表单内容,第三个参数为要上传的文件,可以上传多个文件,这根据需要页定
  2. privatestaticfinalStringTAG="uploadFile";
  3. privatestaticfinalintTIME_OUT=10*1000;//超时时间
  4. privatestaticfinalStringCHARSET="utf-8";//设置编码
  5. /**
  6. *android上传文件到服务器
  7. *@paramfile需要上传的文件
  8. *@paramRequestURL请求的rul
  9. *@return返回响应的内容
  10. */
  11. publicstaticStringuploadFile(Filefile,StringRequestURL)
  12. {
  13. Stringresult=null;
  14. StringBOUNDARY=UUID.randomUUID().toString();//边界标识随机生成
  15. StringPREFIX="--",LINE_END="\r\n";
  16. StringCONTENT_TYPE="multipart/form-data";//内容类型
  17. try{
  18. URLurl=newURL(RequestURL);
  19. HttpURLConnectionconn=(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. DataOutputStreamdos=newDataOutputStream(conn.getOutputStream());
  35. StringBuffersb=newStringBuffer();
  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. InputStreamis=newFileInputStream(file);
  49. byte[]bytes=newbyte[1024];
  50. intlen=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. intres=conn.getResponseCode();
  65. Log.i(TAG,"responsecode:"+res);
  66. if(res==200)
  67. {
  68. Log.e(TAG,"requestsuccess");
  69. InputStreaminput=conn.getInputStream();
  70. StringBuffersb1=newStringBuffer();
  71. intss;
  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,"requesterror");
  81. }
  82. }
  83. }catch(MalformedURLExceptione){
  84. e.printStackTrace();
  85. }catch(IOExceptione){
  86. e.printStackTrace();
  87. }
  88. returnresult;
  89. }

这个方法需要传递一个由图片的path(路径)生成的file格式的数据。和上传地址的url。

首先是本地上传。

[java] view plain copy
  1. /***
  2. *这个是调用android内置的intent,来过滤图片文件,同时也可以过滤其他的
  3. */
  4. Intentintent=newIntent();
  5. intent.setType("image/*");
  6. intent.setAction(Intent.ACTION_GET_CONTENT);
  7. startActivityForResult(intent,selectCode);

这个是调用本地图片库。

返回过后是在 ResultActivty里返回。

[java] view plain copy
  1. protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
  2. super.onActivityResult(requestCode,resultCode,data);
  3. if(selectCode==requestCode){
  4. /**
  5. *当选择的图片不为空的话,在获取到图片的途径
  6. */
  7. Uriuri=data.getData();
  8. Log.i(TAG,"uri="+uri);
  9. try{
  10. String[]pojo={MediaStore.Images.Media.DATA};
  11. Cursorcursor=managedQuery(uri,pojo,null,null,null);
  12. if(cursor!=null)
  13. {
  14. ContentResolvercr=this.getContentResolver();
  15. intcolunm_index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  16. cursor.moveToFirst();
  17. Stringpath=cursor.getString(colunm_index);
  18. /***
  19. *这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了,这样的话,我们判断文件的后缀名
  20. *如果是图片格式的话,那么才可以
  21. */
  22. if(path.endsWith("jpg")||path.endsWith("png"))
  23. {
  24. picPath=path;
  25. Bitmapbitmap=BitmapFactory.decodeStream(cr.openInputStream(uri));
  26. imageView.setImageBitmap(bitmap);
  27. }else{alert();}
  28. }else{alert();}
  29. }catch(Exceptione){
  30. }
  31. super.onActivityResult(requestCode,resultCode,data);
  32. }


取值,并且将图片填充到imageView里。本Activty里全局变量保存picPath。

拍照上传,首先要进入照相机。

[java] view plain copy
  1. destoryBimap();
  2. Stringstate=Environment.getExternalStorageState();
  3. if(state.equals(Environment.MEDIA_MOUNTED)){
  4. intent=newIntent("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

[java] view plain copy
  1. if(cameraCode==requestCode){
  2. Bundlebundle=data.getExtras();
  3. photo=(Bitmap)bundle.get("data");//获取相机返回的数据,并转换为Bitmap图片格式
  4. ByteArrayOutputStreambaos=newByteArrayOutputStream();
  5. photo.compress(Bitmap.CompressFormat.JPEG,100,baos);//把数据写入文件
  6. Uriuri=data.getData();
  7. Log.i(TAG,"uri="+uri);
  8. try{
  9. String[]pojo={MediaStore.Images.Media.DATA};
  10. Cursorcursor=managedQuery(uri,pojo,null,null,null);
  11. if(cursor!=null){
  12. intcolunm_index=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  13. cursor.moveToFirst();
  14. Stringpath=cursor.getString(colunm_index);
  15. if(path!=null){
  16. picPath=path;
  17. imageView.setImageBitmap(photo);
  18. }
  19. }
  20. }catch(Exceptione){
  21. //TODO:handleexception
  22. }
  23. }


此返回值跟上面本地取图片一样。返回picPath,并且将图片填充至imageView。

上传:

[java] view plain copy
  1. Filefile=newFile(saveBefore(picPath));
  2. if(file!=null)
  3. {
  4. Stringrequest=PostFile.uploadFile(file,requestURL);
  5. uploadImage.setText(request);
  6. }
  7. break;

上传之前将图片压缩。

现在附上一些转换方法

[java] view plain copy
  1. privatevoiddestoryBimap(){
  2. if(photo!=null&&!photo.isRecycled()){
  3. photo.recycle();
  4. photo=null;
  5. }
  6. }


[java] view plain copy
  1. /**
  2. *读取路径中的图片,然后将其转化为缩放后的bitmap
  3. *@parampath
  4. */
  5. publicStringsaveBefore(Stringpath){
  6. BitmapFactory.Optionsoptions=newBitmapFactory.Options();
  7. options.inJustDecodeBounds=true;
  8. //获取这个图片的宽和高
  9. Bitmapbitmap=BitmapFactory.decodeFile(path,options);//此时返回bm为空
  10. options.inJustDecodeBounds=false;
  11. //计算缩放比
  12. intbe=(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. returnsaveJPGE_After(bitmap,path);
  20. }
  21. /**
  22. *保存图片为JPEG
  23. *@parambitmap
  24. *@parampath
  25. */
  26. publicStringsaveJPGE_After(Bitmapbitmap,Stringpath){
  27. Filefile=newFile(path);
  28. try{
  29. FileOutputStreamout=newFileOutputStream(file);
  30. if(bitmap.compress(Bitmap.CompressFormat.JPEG,100,out)){
  31. out.flush();
  32. out.close();
  33. }
  34. }catch(FileNotFoundExceptione){
  35. e.printStackTrace();
  36. }catch(IOExceptione){
  37. e.printStackTrace();
  38. }
  39. returnpath;
  40. }

更多相关文章

  1. Android 导入android源码有错,R.java文件不能自动生成解决方法
  2. Android 控件之Gallery和ImageSwitcher图片切换器
  3. Android dex ,xml 文件反编译方法
  4. android/java 计算大文件的sha1值
  5. android中使用Thumbnails批量加载sdcard中的缩略图片

随机推荐

  1. PHP学习笔记(三):mysqli_fetch_row和mysqli_
  2. Mysql查询时,对于数值型字段加单引号会引
  3. mysqlbinlog 查看二进制日志
  4. SQL Server 执行计划操作符详解(1)——断言
  5. 在多个查询和子查询中更正连接语法
  6. SQL语句练习(1)
  7. Mysql order by语句未使用索引的思考
  8. 为什么我不能在此查询中进行任何类型的加
  9. 使用SQL使用从左到右和从右到左混合语言
  10. SQL Server 2005与SQL Server 2000相比性