如何压缩URI图片?

时间:2018-12-03 14:56:45

标签: java android bitmap uri

我对编程还是很陌生,我想将图像导入到我的应用中并在其中显示。问题是,每当我将照片添加到应用程序中时,由于Java中的内存不足错误,应用程序很快就会崩溃。在添加图像之前,我需要先对其进行压缩,但是我绝对不知道如何,有人可以帮助我吗?

我的代码:

MainActivity:

import android.content.ClipData;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Button btn;
    int PICK_IMAGE_MULTIPLE = 1;
    String imageEncoded;
    List<String> imagesEncodedList;
    private GridView gvGallery;
    private GalleryAdapter galleryAdapter;

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

    btn = findViewById(R.id.btn);
    gvGallery = (GridView)findViewById(R.id.gv);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Bild(er) wählen"), PICK_IMAGE_MULTIPLE);
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_camera) {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }

        return true;
    }

    return super.onOptionsItemSelected(item);
}

static final int REQUEST_IMAGE_CAPTURE = 1;

static final int PICK_IMAGE = 1;

//private void dispatchTakePictureIntent() {
//    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
//        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
//    }
//}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {
        // When an Image is picked
        if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
                && null != data) {
            // Get the Image from data

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            imagesEncodedList = new ArrayList<String>();
            if(data.getData()!=null){

                Uri mImageUri=data.getData();

                // Get the cursor
                Cursor cursor = getContentResolver().query(mImageUri,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imageEncoded  = cursor.getString(columnIndex);
                cursor.close();

                ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                mArrayUri.add(mImageUri);
                galleryAdapter = new GalleryAdapter(getApplicationContext(),mArrayUri);
                gvGallery.setAdapter(galleryAdapter);
                gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
                ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery
                        .getLayoutParams();
                mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);

            } else {
                if (data.getClipData() != null) {
                    ClipData mClipData = data.getClipData();
                    ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                    for (int i = 0; i < mClipData.getItemCount(); i++) {

                        ClipData.Item item = mClipData.getItemAt(i);
                        Uri uri = item.getUri();
                        mArrayUri.add(uri);
                        // Get the cursor
                        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                        // Move to first row
                        cursor.moveToFirst();

                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        imageEncoded  = cursor.getString(columnIndex);
                        imagesEncodedList.add(imageEncoded);
                        cursor.close();

                        galleryAdapter = new GalleryAdapter(getApplicationContext(),mArrayUri);
                        gvGallery.setAdapter(galleryAdapter);
                        gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
                        ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery
                                .getLayoutParams();
                        mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);

                    }
                    Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
                }
            }
        } else {
            Toast.makeText(this, "Keine Bilder ausgewählt!",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Fehler", Toast.LENGTH_LONG)
                .show();
    }

    //if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
    //    Bundle extras = data.getExtras();
    //    Bitmap imageBitmap = (Bitmap) extras.get("data");
    //    ImageView mImageView = new ImageView(this);
    //    mImageView.setImageBitmap(imageBitmap);
    //}

    super.onActivityResult(requestCode, resultCode, data);

}
}

GalleryAdapter:

import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import java.util.ArrayList;

public class GalleryAdapter extends BaseAdapter {

private Context ctx;
private int pos;
private LayoutInflater inflater;
private ImageView ivGallery;
ArrayList<Uri> mArrayUri;
public GalleryAdapter(Context ctx, ArrayList<Uri> mArrayUri) {

    this.ctx = ctx;
    this.mArrayUri = mArrayUri;
}

@Override
public int getCount() {
    return mArrayUri.size();
}

@Override
public Object getItem(int position) {
    return mArrayUri.get(position);
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    pos = position;
    inflater = (LayoutInflater) ctx
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View itemView = inflater.inflate(R.layout.gv_item, parent, false);

    ivGallery = (ImageView) itemView.findViewById(R.id.ivGallery);

    ivGallery.setImageURI(mArrayUri.get(position));

    return itemView;
}


}

如果您需要更多信息,请随时提问! 谢谢您的帮助!

2 个答案:

答案 0 :(得分:1)

问题: 您的应用程序存在的问题是android系统无法在屏幕上正确加载相对较大的位图,并且试图这样做会超出分配给该加载过程的内存限制。

解决方案:

快速解决方案How to resize Image in Android?

详细了解

  

注意:有几个遵循最佳实践的库   加载图像。您可以在应用中使用这些库来加载图像   以最优化的方式。我们建议使用Glide库   尽快加载并显示图像。其他   流行的图像加载库包括Square和Fresco的Picasso   来自Facebook。这些库简化了大多数复杂的任务   与位图和Android上其他类型的图像相关联。

点击此处链接:https://developer.android.com/topic/performance/graphics/load-bitmap

答案 1 :(得分:0)

尝试直接自己获取位图,然后对其进行缩放。

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mArrayUri.get(position));

那应该得到位图。

然后,您可以将其缩放到更小的尺寸。我不会提供实现缩放的方法,但是您需要此方法:

Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)