1. 程式人生 > >二級取樣 以及圖片壓縮

二級取樣 以及圖片壓縮

首先 建立一個工具類 用來對圖片進行二級取樣
ImageUtils

package com.example.lenovo.myapplication.Utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class ImageUtils {
    //圖片二級取樣 掉一個方法 三個 引數 路徑 寬 高
    // 此為第一次  寬高取樣
    public static Bitmap scaleBitmap(String filePath, int width, int height){
        //例項化 工程設定
        BitmapFactory.Options options = new BitmapFactory.Options();
        //不載入Bitmap 到記憶體中
        options.inJustDecodeBounds = true;

        BitmapFactory.decodeFile(filePath,options);

        options.inSampleSize=Math.max(options.outHeight/height,options.outWidth/width);

        //第二次載入
        options.inJustDecodeBounds=false;

        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

        return bitmap;
    }

    public static Bitmap compress(Bitmap bitmap,int qual,File fiel){
        Bitmap result = bitmap;
        try {
            //縮放後的
            //bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "tmp.jpg")));
            //壓縮後的,儲存到output檔案
            bitmap.compress(Bitmap.CompressFormat.JPEG, qual, new FileOutputStream(fiel));
            //再次解析壓縮後的圖片
            result = BitmapFactory.decodeFile(fiel.getAbsolutePath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        };
        return result;

    }
}

//其次就能直接在方法裡呼叫 這個圖片的工具類
這裡採用才Fragment裡 進行處理
//Fragment()

package com.example.lenovo.myapplication.Fragment;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.CursorLoader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.example.lenovo.myapplication.R;
import com.example.lenovo.myapplication.Utils.ImageUtils;

import java.io.File;

public class WodeFragment extends Fragment {

    private EditText ekuan;
    private EditText egao;
    private EditText ezhi;
    private Button getimgae;
    private Button show;
    private ImageView imageView;
    private Uri url01;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fra_wode,container,false);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //找到資源ID
        ekuan = view.findViewById(R.id.wode_kuan);
        egao = view.findViewById(R.id.wode_gao);
        ezhi = view.findViewById(R.id.wode_quality);
        getimgae = view.findViewById(R.id.wode_getimage);
        show = view.findViewById(R.id.wode_show);
        imageView = view.findViewById(R.id.wode_image);
        //先獲取圖片
        getimgae.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //開啟相簿許可權
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent,100);
            }
        });
        //生成的監聽
        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //101
                String filePath = getRealPathFromUrl(url01);
                //102  (String filePath, int width, int height)
                Bitmap bitmap = ImageUtils.scaleBitmap(filePath, Integer.parseInt(ekuan.getText().toString()),
                        Integer.parseInt(egao.getText().toString()));
                //103
                bitmap = ImageUtils.compress(bitmap, Integer.parseInt(ezhi.getText().toString()), new File(Environment.getExternalStorageDirectory(), "tmp2.jpg"));

                imageView.setImageBitmap(bitmap);
            }
        });
    }

    private String getRealPathFromUrl(Uri uri){
        //01
        String[] proj ={MediaStore.Images.Media.DATA};
        //02
        CursorLoader cursorLoader = new CursorLoader(getActivity(),uri,proj,null,null,null);
        //03
        Cursor cursor = cursorLoader.loadInBackground();
        //04
        int indexOrThrow = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        //05
        cursor.moveToFirst();
        //06
        return cursor.getString(indexOrThrow);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //07
        if(requestCode == 100) {
            //08
            if(resultCode == getActivity().RESULT_OK) {
                //圖片uri
                url01 = data.getData();
            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}

//同時需要注意配置許可權
//

<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"/>