0

我有一个 ImageButton,当我单击它时,它会给我一个 AlertDialog 来将图像添加到我的 Imagebutton。当我添加图像时,应用程序变得非常缓慢和滞后。如果我想重新选择图像,则应用程序崩溃。有人可以帮我解决这个问题吗?

代码:

public class MainActivity extends Activity {

private final int SELECT_FILE = 1;
private final int REQUEST_CAMERA = 0;
private ImageButton btnImg;

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

    btnImg = (ImageButton) findViewById(R.id.btnAddThumbnail);

    btnImg.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            selectImage();
        }
    });
}

private void selectImage() {
    final CharSequence[] items = { "Take Photo", "Choose from gallery",
            "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Add Photo!");

    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                startActivityForResult(intent, REQUEST_CAMERA);
            }

            else if (items[item].equals("Choose from gallery")) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
            }

            else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == REQUEST_CAMERA) {
            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bm;
                BitmapFactory.Options btmapOptions = new BitmapFactory.Options();

                bm = BitmapFactory.decodeFile(f.getAbsolutePath(),btmapOptions);

                // bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
                btnImg.setImageBitmap(bm);
                btnImg.setScaleType(ScaleType.CENTER_INSIDE);

                String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
                f.delete();
                OutputStream fOut = null;
                File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                try {
                    fOut = new FileOutputStream(file);
                    bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                    fOut.flush();
                    fOut.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == SELECT_FILE) {
            Uri selectedImageUri = data.getData();

            String tempPath = getPath(selectedImageUri, MainActivity.this);
            Bitmap bm;
            BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
            bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
            btnImg.setImageBitmap(bm);
            btnImg.setScaleType(ScaleType.CENTER_INSIDE);
        }
    }
}

public String getPath(Uri uri, Activity activity) {
    String[] projection = { MediaColumns.DATA };
    Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

}

崩溃后的错误:

05-04 20:45:02.890: W/dalvikvm(22576): threadid=1: 线程退出未捕获异常 (group=0x41d9f2a0) 05-04 20:45:02.895: E/AndroidRuntime(22576): 致命异常: main 05-04 20:45:02.895: E/AndroidRuntime(22576): java.lang.OutOfMemoryError 05-04 20:45:02.895: E/AndroidRuntime(22576): 在 android.graphics.BitmapFactory.nativeDecodeStream(Native Method) 05 -04 20:45:02.895: E/AndroidRuntime(22576): 在 android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:650) 05-04 20:45:02.895: E/AndroidRuntime(22576): 在 android.graphics .BitmapFactory.decodeFile(BitmapFactory.java:389) 05-04 20:45:02.895: E/AndroidRuntime(22576): at com.example.spui.MainActivity.onActivityResult(MainActivity.java:95) 05-04 20:45 :02.895: E/AndroidRuntime(22576): 在 android.app.Activity.dispatchActivityResult(Activity.java:5390) 05-04 20:45:02.895: E/AndroidRuntime(22576): 在 android.app.ActivityThread.deliverResults(ActivityThread.java:3178) 05-04 20:45:02.895: E/AndroidRuntime(22576): 在 android.app.ActivityThread.handleSendResult (ActivityThread.java:3225) 05-04 20:45:02.895: E/AndroidRuntime(22576): 在 android.app.ActivityThread.access$1100(ActivityThread.java:140) 05-04 20:45:02.895: E/ AndroidRuntime(22576): 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1275) 05-04 20:45:02.895: E/AndroidRuntime(22576): 在 android.os.Handler.dispatchMessage(Handler.java :99) 05-04 20:45:02.895: E/AndroidRuntime(22576): 在 android.os.Looper.loop(Looper.java:137) 05-04 20:45:02.895: E/AndroidRuntime(22576):在 android.app.ActivityThread.main(ActivityThread.java:4898) 05-04 20:45:02.895: E/AndroidRuntime(22576): 在 java.lang.reflect.Method。invokeNative(本机方法)05-04 20:45:02.895:E/AndroidRuntime(22576):在 java.lang.reflect.Method.invoke(Method.java:511)05-04 20:45:02.895:E/AndroidRuntime (22576): 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006) 05-04 20:45:02.895: E/AndroidRuntime(22576): 在 com.android.internal.os。 ZygoteInit.main(ZygoteInit.java:773) 05-04 20:45:02.895: E/AndroidRuntime(22576): at dalvik.system.NativeStart.main(Native Method)773)05-04 20:45:02.895:E/AndroidRuntime(22576):在 dalvik.system.NativeStart.main(本机方法)773)05-04 20:45:02.895:E/AndroidRuntime(22576):在 dalvik.system.NativeStart.main(本机方法)

4

1 回答 1

3

可能是图像太大而您的内存不足。一些设备以非常大的图像尺寸和大尺寸记录图像,这反过来又会导致您遇到内存问题。处理从网络下载的图像时也会发生同样的事情。

我会Bitmap.createScaledBitmap在设置之前使用 API 方法缩小位图以缩小位图。

这里有一个很好的 SO 帖子Android: Resize a large bitmap file to scaled output file

我还想补充一点,多亏了一个很棒的库AndroidQuery,你可以让你的生活变得更简单!我在下面添加了一些代码来展示它如何与您的代码段一起使用。这里有一篇完整的博客文章http://blog.androidquery.com/2011/05/down-sample-images-to-avoid-out-of.html

File file = new File(Environment.getExternalStorageDirectory().toString());       
//load image from file, down sample to target width of 300 pixels and set it to the Imageview
aq.id(R.id.avatar).image(file, 300);
于 2013-05-04T19:52:35.223 回答