1. 程式人生 > >圖片二次取樣

圖片二次取樣

MainActivity頁面

package com.example.image;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.CursorLoader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private EditText width;//寬
    private EditText height;//高
    private EditText quality;//質量

    private Button getImage;//獲取圖片
    private Button show;//顯示圖片
    private ImageView image;

    private final int PICK_IMAGE = 100;
    private Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Bitmap bitmpa;

        //bitmpa.compress(Bitmap.CompressFormat.JPEG, 70, );

        width = findViewById(R.id.width);
        height = findViewById(R.id.height);
        quality = findViewById(R.id.quality);

        getImage = findViewById(R.id.get_image);
        show = findViewById(R.id.show);

        image = findViewById(R.id.image);

        getImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, PICK_IMAGE);
            }
        });


        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String filePath = getRealPathFromURI(uri);

                //二次取樣
                Log.i("TEST",filePath);
                Bitmap bitmap = ImageUtil.scaleBitmap(filePath, Integer.parseInt(width.getText().toString()), Integer.parseInt(height.getText().toString()));

                bitmap = ImageUtil.compress(bitmap, Integer.parseInt(quality.getText().toString()), new File(Environment.getExternalStorageDirectory(), "tmp2.jpg"));
                image.setImageBitmap(bitmap);
                //BitmapFactory.de
                //質量壓縮

                //展示
            }
        });
    }

    private String getRealPathFromURI(Uri contentUri) { //傳入圖片uri地址
        String[] proj = { MediaStore.Images.Media.DATA };
        CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode == PICK_IMAGE) {
            if(resultCode == RESULT_OK) {
                //圖片uri
                uri = data.getData();
            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

工具類ImageUtil

 package com.example.image;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

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

public class ImageUtil {

    //圖片二次取樣
    public static Bitmap scaleBitmap(String filePath, int width, int height) {
        //進行兩次decode
        //第一次decode,只解析bitmap的寬高資訊

        //縮小圖片大小, 降低記憶體佔用
        BitmapFactory.Options opts = new BitmapFactory.Options();
        //指定只解析bitmap的邊界資訊,不載入bitmap到記憶體中
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, opts);
        //寬高資訊
        //1920 1080
        //256 256
        //opts.outWidth;
        //opts.outHeight;
        //通過圖片的真實寬高資訊  和 需要的寬高比,產生一個比例
        opts.inSampleSize = Math.max(opts.outHeight / height, opts.outWidth / width);

        //第二次載入圖片: 真正載入圖片
        opts.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(filePath, opts);
        return bitmap;
    }

    //tup質量壓縮: 只改變檔案大小,基本不改變記憶體佔用
    public static Bitmap compress(Bitmap bitmap, int qual, File output) {
        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(output));
            //再次解析壓縮後的圖片
            result = BitmapFactory.decodeFile(output.getAbsolutePath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        };
        return result;
    }
}