欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android实现上传本地图片到网络功能

程序员文章站 2023-12-14 22:40:16
本文实例为大家分享了android上传本地图片到网络的具体代码,供大家参考,具体内容如下 首先这里用到了okhttp 所以需要一个依赖: compile '...

本文实例为大家分享了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, 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, 85, 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, 0, 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, null, 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, 0, 0, bitmap.getwidth(), bitmap.getheight(), m, true); 
      } 
      float scalevalue = (float) specifiedwidth / bitmap.getwidth(); 
//      等比压缩 
      m.setscale(scalevalue, scalevalue); 
      bitmap = bitmap.createbitmap(bitmap, 0, 0, bitmap.getwidth(), bitmap.getheight(), m, true); 
      return bitmap; 
    } catch (outofmemoryerror e) { 
      e.printstacktrace(); 
      return null; 
    } catch (exception e) { 
      e.printstacktrace(); 
      return null; 
    } 
 
 
  } 
 
 
  /** 
   * 读取图片属性:旋转的角度 
   * 
   * @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, outputstream outstream) throws exception { 
    try { 
      byte[] buffer = new byte[1024]; 
      int len = 0; 
      while ((len = inputstream.read(buffer)) != -1) { 
        outstream.write(buffer, 0, 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; 
    } 
  } 
} 

这样就可以上传图片到网络了!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: