您的位置:首页 > 移动开发 > Android开发

android 图片转Base64压缩上传

2016-08-18 11:32 549 查看
首先得到图片路径 photoPath,

String base64Str = Bitmap2StrByBase64(compressImageFromFile(photoPath));    

 private Bitmap compressImageFromFile(String srcPath) {

        BitmapFactory.Options newOpts = new BitmapFactory.Options();

        newOpts.inJustDecodeBounds = true;//只读边,不读内容

        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

        newOpts.inJustDecodeBounds = false;

        int w = newOpts.outWidth;

        int h = newOpts.outHeight;

        float hh = 800f;//

        float ww = 480f;//

        int be = 1;

        if (w > h && w > ww) {

            be = (int) (newOpts.outWidth / ww);

        } else if (w < h && h > hh) {

            be = (int) (newOpts.outHeight / hh);

        }

        if (be <= 0)

            be = 1;

        newOpts.inSampleSize = be;//设置采样率

        newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888;//该模式是默认的,可不设

        newOpts.inPurgeable = true;// 同时设置才会有效

        newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收

        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);

//      return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩

        //其实是无效的,大家尽管尝试

        return bitmap;

    }

 public String Bitmap2StrByBase64(Bitmap bit){

        ByteArrayOutputStream bos=new ByteArrayOutputStream();

        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩

        byte[] bytes=bos.toByteArray();

        bos.reset();  // TODO     有的图片本身不大压缩后反而变大, 暂未解决, 貌似没个卵用

        return Base64.encodeToString(bytes, Base64.DEFAULT);

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android base64 压缩 图片