1. 程式人生 > >二次取樣+質量壓縮

二次取樣+質量壓縮

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

2.工具類

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

3.佈局

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="選擇圖片"
        android:id="@+id/get_image"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/width"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/get_image"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/height"
        android:text="256"
        android:hint="輸入寬度"/>

    <EditText
        android:id="@+id/height"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="256"
        app:layout_constraintTop_toBottomOf="@id/get_image"
        app:layout_constraintLeft_toRightOf="@id/width"
        app:layout_constraintRight_toLeftOf="@id/quality"
        android:hint="輸入高度"/>

    <EditText
        android:id="@+id/quality"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="70"
        app:layout_constraintTop_toBottomOf="@id/get_image"
        app:layout_constraintLeft_toRightOf="@id/height"
        app:layout_constraintRight_toRightOf="parent"
        android:hint="輸入質量"/>

    <Button
        android:id="@+id/show"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/height"
        android:text="生成"/>

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/show"
        app:layout_constraintBottom_toBottomOf="parent"/>

</android.support.constraint.ConstraintLayout>

4.配置檔案

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