本文实例为大家分享了androID上传本地图片到网络的具体代码,供大家参考,具体内容如下
首先这里用到了Okhttp 所以需要一个依赖:
compile 'com.squareup.okhttp3:okhttp:3.9.0'
xml布局
<?xml version="1.0" enCoding="utf-8"?> <linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:app="http://schemas.androID.com/apk/res-auto" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:orIEntation="vertical" androID:layout_height="match_parent" tools:context="com.bwei.czx.czx10.MainActivity"> <button androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:ID="@+ID/photo"/> <button androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:ID="@+ID/camear"/> </linearLayout>
AndroIDManifest.xml中:权限
<uses-permission androID:name="androID.permission.INTERNET"/> <uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission androID:name="androID.permission.READ_EXTERNAL_STORAGE"/>
MainActivity中:
oncreat:
@OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); findVIEwByID(R.ID.photo).setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw vIEw) { tophoto(); } }); findVIEwByID(R.ID.camear).setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw vIEw) { toCamera(); } }); }
和oncreat同级的方法:
public voID postfile(file file){ // sdcard/dliao/aaa.jpg String path = file.getabsolutePath() ; String [] split = path.split("\/"); MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); OkhttpClIEnt clIEnt = new OkhttpClIEnt(); Requestbody requestbody = new Multipartbody.Builder() .setType(Multipartbody.FORM) // file .addFormDataPart("imagefilename",split[split.length-1]) .addFormDataPart("image",split[split.length-1],Requestbody.create(MEDIA_TYPE_PNG,file)) .build(); Request request = new Request.Builder().post(requestbody).url("http://qhb.2dyt.com/Bwei/upload").build(); clIEnt.newCall(request).enqueue(new Callback() { @OverrIDe public voID onFailure(Call call,IOException e) { } @OverrIDe public voID onResponse(Call call,Response response) throws IOException { System.out.println("response = " + response.body().string()); } }); } static final int INTENTFORCAMERA = 1 ; static final int INTENTFORPHOTO = 2 ; public String LocalPhotoname; public String createLocalPhotoname() { LocalPhotoname = System.currentTimeMillis() + "face.jpg"; return LocalPhotoname ; } public voID toCamera(){ try { Intent intentNow = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri uri = null ; // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //针对Android7.0,需要通过fileProvIDer封装过的路径,提供给外部调用 // uri = fileProvIDer.getUriForfile(UploadPhotoActivity.this,"com.bw.dliao",SDCardUtils.getMyFacefile(createLocalPhotoname()));//通过fileProvIDer创建一个content类型的Uri,进行封装 // }else { uri = Uri.fromfile(SDCardUtils.getMyFacefile(createLocalPhotoname())) ; // } intentNow.putExtra(MediaStore.EXTRA_OUTPUT,uri); startActivityForResult(intentNow,INTENTFORCAMERA); } catch (Exception e) { e.printstacktrace(); } } /** * 打开相册 */ public voID tophoto(){ try { createLocalPhotoname(); Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT); getAlbum.setType("image/*"); startActivityForResult(getAlbum,INTENTFORPHOTO); } catch (Exception e) { e.printstacktrace(); } } @OverrIDe protected voID onActivityResult(int requestCode,int resultCode,Intent data) { super.onActivityResult(requestCode,resultCode,data); switch (requestCode) { case INTENTFORPHOTO: //相册 try { // 必须这样处理,不然在4.4.2手机上会出问题 Uri originalUri = data.getData(); file f = null; if (originalUri != null) { f = new file(SDCardUtils.photoCacheDir,LocalPhotoname); String[] proj = {MediaStore.Images.Media.DATA}; Cursor actualimagecursor = this.getContentResolver().query(originalUri,proj,null,null); if (null == actualimagecursor) { if (originalUri.toString().startsWith("file:")) { file file = new file(originalUri.toString().substring(7,originalUri.toString().length())); if(!file.exists()){ //地址包含中文编码的地址做utf-8编码 originalUri = Uri.parse(URLDecoder.decode(originalUri.toString(),"UTF-8")); file = new file(originalUri.toString().substring(7,originalUri.toString().length())); } fileinputStream inputStream = new fileinputStream(file); fileOutputStream outputStream = new fileOutputStream(f); copyStream(inputStream,outputStream); } } else { // 系统图库 int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); actualimagecursor.movetoFirst(); String img_path = actualimagecursor.getString(actual_image_column_index); if (img_path == null) { inputStream inputStream = this.getContentResolver().openinputStream(originalUri); fileOutputStream outputStream = new fileOutputStream(f); copyStream(inputStream,outputStream); } else { file file = new file(img_path); fileinputStream inputStream = new fileinputStream(file); fileOutputStream outputStream = new fileOutputStream(f); copyStream(inputStream,outputStream); } } Bitmap bitmap = ImageResizeUtils.resizeImage(f.getabsolutePath(),1080); int wIDth = bitmap.getWIDth(); int height = bitmap.getHeight(); fileOutputStream fos = new fileOutputStream(f.getabsolutePath()); if (bitmap != null) { if (bitmap.compress(Bitmap.CompressFormat.JPEG,85,fos)) { fos.close(); fos.flush(); } if (!bitmap.isRecycled()) { bitmap.isRecycled(); } System.out.println("f = " + f.length()); postfile(f); } } } catch (Exception e) { e.printstacktrace(); } break; case INTENTFORCAMERA: // 相机 try { //file 就是拍照完 得到的原始照片 file file = new file(SDCardUtils.photoCacheDir,LocalPhotoname); Bitmap bitmap = ImageResizeUtils.resizeImage(file.getabsolutePath(),1080); int wIDth = bitmap.getWIDth(); int height = bitmap.getHeight(); fileOutputStream fos = new fileOutputStream(file.getabsolutePath()); if (bitmap != null) { if (bitmap.compress(Bitmap.CompressFormat.JPEG,fos)) { fos.close(); fos.flush(); } if (!bitmap.isRecycled()) { //通知系统 回收bitmap bitmap.isRecycled(); } System.out.println("f = " + file.length()); postfile(file); } } catch (Exception e) { e.printstacktrace(); } break; } } public static voID copyStream(inputStream inputStream,OutputStream outStream) throws Exception { try { byte[] buffer = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { outStream.write(buffer,len); } outStream.flush(); } catch (IOException e) { e.printstacktrace(); }finally { if(inputStream != null){ inputStream.close(); } if(outStream != null){ outStream.close(); } } }
ImageResizeUtils中:
package com.bwei.czx.czx10; import androID.graphics.Bitmap; import androID.graphics.BitmapFactory; import androID.graphics.Matrix; import androID.media.ExifInterface; import java.io.file; import java.io.fileinputStream; import java.io.fileNotFoundException; import java.io.IOException; import java.io.inputStream; import java.io.OutputStream; import static androID.graphics.BitmapFactory.decodefile; /** * Created by czx on 2017/9/27. */ public class ImageResizeUtils { /** * 照片路径 * 压缩后 宽度的尺寸 * @param path * @param specifIEDWIDth */ public static Bitmap resizeImage(String path,int specifIEDWIDth) throws Exception { Bitmap bitmap = null; fileinputStream inStream = null; file f = new file(path); System.out.println(path); if (!f.exists()) { throw new fileNotFoundException(); } try { inStream = new fileinputStream(f); int degree = readPictureDegree(path); BitmapFactory.Options opt = new BitmapFactory.Options(); //照片不加载到内存 只能读取照片边框信息 opt.inJustDecodeBounds = true; // 获取这个图片的宽和高 decodefile(path,opt); // 此时返回bm为空 int inSampleSize = 1; final int wIDth = opt.outWIDth; // wIDth 照片的原始宽度 specifIEDWIDth 需要压缩的宽度 // 1000 980 if (wIDth > specifIEDWIDth) { inSampleSize = (int) (wIDth / (float) specifIEDWIDth); } // 按照 565 来采样 一个像素占用2个字节 opt.inPreferredConfig = Bitmap.Config.RGB_565; // 图片加载到内存 opt.inJustDecodeBounds = false; // 等比采样 opt.inSampleSize = inSampleSize; // opt.inPurgeable = true; // 容易导致内存溢出 bitmap = BitmapFactory.decodeStream(inStream,opt); // bitmap = BitmapFactory.decodefile(path,opt); if (inStream != null) { try { inStream.close(); } catch (IOException e) { e.printstacktrace(); } finally { inStream = null; } } if (bitmap == null) { return null; } Matrix m = new Matrix(); if (degree != 0) { //给Matrix 设置旋转的角度 m.setRotate(degree); bitmap = Bitmap.createBitmap(bitmap,bitmap.getWIDth(),bitmap.getHeight(),m,true); } float scaleValue = (float) specifIEDWIDth / bitmap.getWIDth(); // 等比压缩 m.setScale(scaleValue,scaleValue); bitmap = Bitmap.createBitmap(bitmap,true); return bitmap; } catch (OutOfMemoryError e) { e.printstacktrace(); return null; } catch (Exception e) { e.printstacktrace(); return null; } } /** * 读取@R_502_6363@:旋转的角度 * * @param path 源信息 * 图片绝对路径 * @return degree旋转的角度 */ public static int readPictureDegree(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orIEntation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_norMAL); switch (orIEntation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printstacktrace(); } return degree; } public static voID copyStream(inputStream inputStream,len); } outStream.flush(); } catch (IOException e) { e.printstacktrace(); }finally { if(inputStream != null){ inputStream.close(); } if(outStream != null){ outStream.close(); } } } }
SDcardutils中:
package com.bwei.czx.czx10; import androID.os.Environment; import androID.os.StatFs; import java.io.file; import java.io.IOException; /** * Created by czx on 2017/9/27. */ public class SDCardUtils { public static final String DliAO = "dliao" ; public static file photoCacheDir = SDCardUtils.createCacheDir(Environment.getExternalStorageDirectory().getabsolutePath() + file.separator + DliAO); public static String cachefilename = "myphototemp.jpg"; public static boolean isSDCardExist() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } public static voID delFolder(String folderPath) { try { delAllfile(folderPath); String filePath = folderPath; filePath = filePath.toString(); file myfilePath = new file(filePath); myfilePath.delete(); } catch (Exception e) { e.printstacktrace(); } } public static boolean delAllfile(String path) { boolean flag = false; file file = new file(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } String[] tempList = file.List(); file temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(file.separator)) { temp = new file(path + tempList[i]); } else { temp = new file(path + file.separator + tempList[i]); } if (temp.isfile()) { temp.delete(); } if (temp.isDirectory()) { delAllfile(path + "/" + tempList[i]);// 先删除文件夹里面的文件 delFolder(path + "/" + tempList[i]);// 再删除空文件夹 flag = true; } } return flag; } public static boolean deleteoldAllfile(final String path) { try { new Thread(new Runnable() { @OverrIDe public voID run() { delAllfile(Environment.getExternalStorageDirectory() + file.separator + DliAO); } }).start(); } catch (Exception e) { e.printstacktrace(); return false; } return true; } /** * 给定字符串获取文件夹 * * @param dirPath * @return 创建的文件夹的完整路径 */ public static file createCacheDir(String dirPath) { file dir = new file(dirPath);; if(isSDCardExist()){ if (!dir.exists()) { dir.mkdirs(); } } return dir; } public static file createNewfile(file dir,String filename) { file f = new file(dir,filename); try { // 出现过目录不存在的情况,重新创建 if (!dir.exists()) { dir.mkdirs(); } f.createNewfile(); } catch (IOException e) { e.printstacktrace(); } return f; } public static file getCachefile() { return createNewfile(photoCacheDir,cachefilename); } public static file getMyFacefile(String filename) { return createNewfile(photoCacheDir,filename); } /** * 获取SDCARD剩余存储空间 * * @return 0 sd已被挂载占用 1 sd卡内存不足 2 sd可用 */ public static int getAvailableExternalStorageSize() { if (isSDCardExist()) { file path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); long memorySize = availableBlocks * blockSize; if(memorySize < 10*1024*1024){ return 1; }else{ return 2; } } else { return 0; } } }
这样就可以上传图片到网络了!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的android实现上传本地图片到网络功能全部内容,希望文章能够帮你解决android实现上传本地图片到网络功能所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)