1. 程式人生 > >二次取樣+AsyncTask

二次取樣+AsyncTask

#1.主頁面

package com.bw.ymy.imageloader;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
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.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
private EditText width;
private EditText height;
private Button getImage;
private Button show;
private Uri uri;
private ImageView image;
private String w;
private String h;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

    width = findViewById(R.id.width);
    height = findViewById(R.id.height);
    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, 100);
                                    }


    });
    //點選生成
    show.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //獲取輸入框的值
            w = width.getText().toString();
            h = height.getText().toString();
            if (w.equals("") || h.equals("")) {
                Toast.makeText(MainActivity.this, "請輸入寬,高", Toast.LENGTH_SHORT).show();
            } else {
                if (uri != null) {
                    String filePath = getUri(uri);
                    NetUtils.getIntance().scaleBitmap(filePath, Integer.parseInt(w),
                            Integer.parseInt(h), new NetUtils.CallBack() {
                                @Override
                                public void onSuccess(Bitmap bitmap) {
                                    image.setImageBitmap(bitmap);
                                }
                            }
                    );
                } else {
                    Toast.makeText(MainActivity.this, "請選擇圖片", Toast.LENGTH_SHORT).show();
                }
            }
        }
    });
}

//傳入圖片路徑
private String getUri(Uri contentUri) {
    String[] pr = {MediaStore.Images.Media.DATA};
    CursorLoader loader = new CursorLoader(this, contentUri, pr, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(index);
}

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

}

#2.工具類
package com.bw.ymy.imageloader;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

public class NetUtils {
private static NetUtils intance;

public NetUtils() {
}

public static NetUtils getIntance() {
    if(intance == null){
        intance = new NetUtils();
    }
    return intance;
}
//圖片二次取樣
public Bitmap scaleBitmap(String filePath,int width,int height){
    //第一次直解析bitmap的寬高資訊
    BitmapFactory.Options op = new BitmapFactory.Options();
    //指定只解析bitmap的邊界資訊,不載入bitmap到記憶體中
    op.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath,op);
    //通過圖片的真實寬高資訊和需要的寬高產生比例
    op.inSampleSize = Math.max(op.outHeight/height,op.outWidth/width);
    //第二次真正載入圖片
    op.inJustDecodeBounds = false;
    Bitmap bitmap = BitmapFactory.decodeFile(filePath,op);
    return bitmap;
}
//定義介面
public interface CallBack{
    void onSuccess(Bitmap bitmap);
}
@SuppressLint("StaticFieldLeak")
public void scaleBitmap(String filePath, final int width, final int height, final CallBack callBack){
    new AsyncTask<String,Void,Bitmap>(){
        @Override
        protected Bitmap doInBackground(String... strings) {
            return scaleBitmap(strings[0],width,height);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            callBack.onSuccess(bitmap);
        }
    }.execute(filePath);
}

}

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

<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:hint="輸入寬度"/>

<EditText
    android:id="@+id/height"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toBottomOf="@id/get_image"
    app:layout_constraintLeft_toRightOf="@id/width"
    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>
//加許可權