android 图片压缩,base64转换上传

作者: 666swb | 来源:发表于2016-07-08 16:15 被阅读7236次

    可以把1.5M的压缩到100Kb这样哦,可以看到最后log,压缩后的大小为100kb以内

    github地址:https://github.com/George-Soros/ImageTest

    package com.tj.imagetest;
    
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import butterknife.Bind;
    import butterknife.ButterKnife;
    import uk.co.senab.photoview.PhotoView;
    import uk.co.senab.photoview.PhotoViewAttacher;
    
    public class MainActivity extends AppCompatActivity {
    
        @Bind(R.id.btn_photo)
        Button mBtnPhoto;
        @Bind(R.id.img_photo)
        PhotoView mPhotoView;
    
        private Uri mImageUri; //图片路径Uri
        private String mImagePath;
        private String mFileName; //图片名称
        public static final int TAKE_PHOTO = 1;
        public static final int CROP_PHOTO = 2;
        private Bitmap mBitmap;
        private PhotoViewAttacher mAttacher;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            ButterKnife.bind(this);
            mBtnPhoto.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startCamera();
                }
            });
        }
    
        /***
        * 启动相机去拍摄, 并截图
        *
        */
        public void startCamera(){
            //图片名称 时间命名
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = new Date(System.currentTimeMillis());
            mFileName = format.format(date);
            Log.d("data", "mFileName=" + mFileName);
    
            //存储至DCIM文件夹
            File path = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM);
            File outputImage = new File(path, mFileName +".jpg");
            try {
                if(outputImage.exists()) {
                    outputImage.delete();
                }
                outputImage.createNewFile();
                mImagePath = path + "/"+ mFileName + ".jpg";
                Log.d("data","mImagePath="+mImagePath);
            } catch(IOException e) {
                e.printStackTrace();
            }
            //将File对象转换为Uri并启动照相程序
            mImageUri = Uri.fromFile(outputImage);
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); //照相
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); //指定图片输出地址
            startActivityForResult(intent,CROP_PHOTO); //启动照相
            //拍完照startActivityForResult() 结果返回onActivityResult()函数
        }
    
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode != RESULT_OK) {
                return;
            }
            switch(requestCode) {
                case TAKE_PHOTO:
                    Intent intent = new Intent("com.android.camera.action.CROP"); //剪裁
                    intent.setDataAndType(mImageUri, "image/*");
                    intent.putExtra("scale", true);
                    //设置宽高比例
                    intent.putExtra("aspectX", 1);
                    intent.putExtra("aspectY", 1);
                    //设置裁剪图片宽高
                    intent.putExtra("outputX", 400);
                    intent.putExtra("outputY", 340);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
                    //广播刷新相册
                    Intent intentBc = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    intentBc.setData(mImageUri);
                    this.sendBroadcast(intentBc);
                    startActivityForResult(intent, CROP_PHOTO); //设置裁剪参数显示图片至ImageView
                    break;
                case CROP_PHOTO:
                    try {
                        //图片解析成Bitmap对象
                        mBitmap = BitmapFactory.decodeStream(
                                getContentResolver().openInputStream(mImageUri));
                        mAttacher = new PhotoViewAttacher(mPhotoView);
                        mPhotoView.setImageBitmap(mBitmap);
                        mAttacher.update();
    
                        //file:///storage/emulated/0/DCIM/20160707132811.jpg
                        Log.d("d","mImagePath="+mImagePath);
    
                        ImageUtils.bitmapToString(mImagePath);
    
                    } catch(FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    
    }
    
    package com.tj.imagetest;
    
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.util.Base64;
    import android.util.Log;
    
    import java.io.ByteArrayOutputStream;
    
    /**
    * Created by Administrator on 2016/7/7 0007.
    */
    public class ImageUtils {
    
        // 根据路径获得图片并压缩,返回bitmap用于显示
        public static Bitmap getSmallBitmap(String filePath) {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, options);
    
            // Calculate inSampleSize
            options.inSampleSize = calculateInSampleSize(options, 480, 800);
    
            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;
    
            return BitmapFactory.decodeFile(filePath, options);
        }
    
        //计算图片的缩放值
        public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
            final int height = options.outHeight;
            final int width = options.outWidth;
            int inSampleSize = 1;
    
            if (height > reqHeight || width > reqWidth) {
                final int heightRatio = Math.round((float) height/ (float) reqHeight);
                final int widthRatio = Math.round((float) width / (float) reqWidth);
                inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
            }
            return inSampleSize;
        }
    
    //把bitmap转换成String
    public static String bitmapToString(String filePath) {
        Bitmap bm = getSmallBitmap(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
        //1.5M的压缩后在100Kb以内,测试得值,压缩后的大小=94486字节,压缩后的大小=74473字节
        //这里的JPEG 如果换成PNG,那么压缩的就有600kB这样
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        Log.d("d", "压缩后的大小=" + b.length);
        return Base64.encodeToString(b, Base64.DEFAULT);
    }
    
        
    }
    

    其中PhotoView不明白,看http://www.jianshu.com/p/6e38712e310f

    相关文章

      网友评论

      • Jay_Lwp:这个工具类不错
      • bdf804c76982:遇到过这样的问题吗。三星手机拍照后的图片经过转换后图片旋转90度
      • 570cb87f4094:你好,请问下,你知道如何才能上传原图么,我现在的项目里,上传的图片后的质量和原图比,有点寒碜
      • 你好好爱他我四海为家:但是上传部分没有啊?
      • 你好好爱他我四海为家:服务器那边不解压会失真吗?
        666swb: @你好好爱他我四海为家 不会的
      • 9efe1db2c646:我之前我遇到过这样的问题,但是更好的办法是在Camera属性里面设置拍摄的图片尺寸,基本所有手机支持640*480这个尺寸,设置一下就可以直接获得了,不需要压缩,这样太耗时了
        你好好爱他我四海为家:服务器那边不解压会失真吗?
        142c156a8e7f:具体怎么做?
        666swb:@彼时芒种 回去试试,谢谢,😄
      • 浮华染流年:来份demo博主
        666swb: @浮华染流年 github上下一下
      • YungFan:你这样压缩以后,传到服务器端以后质量如何?
        YungFan:@吃不饱的水手 :+1::+1:
        666swb: @YungFan 传到服务器,图片清晰,多次测试通过

      本文标题:android 图片压缩,base64转换上传

      本文链接:https://www.haomeiwen.com/subject/sehrjttx.html