图片上传到网络上

来源:互联网 发布:三星系统升级软件 编辑:程序博客网 时间:2024/05/21 02:34

首先我们要用到的是OKHttp网络我们就用到一个OKHttp的依赖将这个依赖 放到Build.gradle 本App中


compile 'com.squareup.okhttp3:okhttp:3.9.0'



权限

  <uses-permission android:name="android.permission.INTERNET"/>    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>



我那在activity_main.xml 布局文件中写入了两个点击事件一个是《打开相册》《打开照片》两个BUtton


<?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:layout_height="match_parent"    tools:context="test.bwie.com.wzq20171507dproject2.MainActivity">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/photo"        android:text="打开相册"/>    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/camear"        android:text="打开相机"/></LinearLayout>


我们就要在MainActivity 中找到ID 并做点击  调用操作方法


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();            }        });



定义的相机和相册的常量值。 和 返回String类型的 文件名的jpg格式


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(){        Intent intentNOW = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);        Uri uri =null;        uri = Uri.fromFile(SDCardUtils.getMyFaceFile(CreateLocalPhotoName()));        intentNOW.putExtra(MediaStore.EXTRA_OUTPUT, uri);        startActivityForResult(intentNOW,INTENTFORCAMERA);    }    /**     * 打开相册     */    public void toPhoto(){        CreateLocalPhotoName();        Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);        getAlbum.setType("image/*");        startActivityForResult(getAlbum,INTENTFORPHOTO);    }


其中我么还用到了 在点击相机的时候调用的这个类对sdcard或内存上找到图片地址

SDCardUtils 类:
package test.bwie.com.wzq20171507dproject2;import android.os.Environment;import android.os.StatFs;import java.io.File;import java.io.IOException;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;        }    }}


对上传图片的压缩
ImageResizeUtils 类:
package test.bwie.com.wzq20171507dproject2;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;public class ImageResizeUtils {    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();            }        }    }}




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)                .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());            }        });    }

还有读和写的帮助方法

//读和写的帮助方法    public static  void copyStreaam(InputStream is, OutputStream os){        try {            byte[] buffer = new byte[1024];            int len= 0;            while((len= is.read(buffer))!=-1){                os.write(buffer,0,len);            }            os.flush();        } catch (IOException e) {            e.printStackTrace();        }finally {            if (is != null && os != null) {                try {                    os.close();                    is.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }

最后我们OnActivityResult 返回的方法   根据返回的requestCode  判断   定义的相机和相册的常量值


 @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;        }    }