Android轉換為位圖崩潰 (Android Converting to bitmap crash)


問題描述

Android轉換為位圖崩潰 (Android Converting to bitmap crash)

Ok so I am supposed to make an android application but for some reason, I cannot convert my picture to a bitmap image. It's a .png image and when I try to convert it in my code, my application just crashes, no errorcode or nothing. Ive tried fixing it a ton of times, but I'm just not that good in programming and I need help, it just won't work.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (requestCode == FOTO_NEMEN && resultCode == RESULT_OK)
                {
                    final File file = temp;
                    try {
                        String urienzo = "file:///sdcard/DCIM/2013‑01‑30_13‑27‑28.png";
                        Uri uri = Uri.parse(urienzo);
                        Bitmap foto = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                        if (foto == null) {
                            Toast.makeText(this, Uri.fromFile(file).toString(), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        foto.compress(Bitmap.CompressFormat.PNG, 0 , bos);
                        final byte[] bytes = bos.toByteArray();
                        bos.close();
                        AsyncTask<Void,Void,Void> taak = new AsyncTask<Void,Void,Void>() {
                            @Override
                            protected Void doInBackground(Void... params) {
                                stuurAfbeelding(bytes);
                                return null;
                            }   
                        };
                        taak.execute(null,null);
                    } catch (IOException e) {
                        Log.e("Snapper","Fout bij foto nemen: " + e);
                    }
                }
            }

Whenever I get to the bitmap foto part, it crashes my application without any error message. The reason my URI is hardcoded is because I think the URI.fromfile was giving me the wrong URI, so I wanted to be sure. Now it just crashes and I have no idea what is wrong with my code. Could someone aid me?

‑‑‑‑‑

參考解法

方法 1:

In my opinion you get an outOfMemmoryError.

for getting bitmap from uri you should use something like this:

public static Bitmap getThumbnail(Uri uri) throws FileNotFoundException, IOException{
    InputStream input = this.getContentResolver().openInputStream(uri);

    BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
    onlyBoundsOptions.inJustDecodeBounds = true;
    onlyBoundsOptions.inDither=true;//optional
    onlyBoundsOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
    BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
    input.close();
    if ((onlyBoundsOptions.outWidth == ‑1) || (onlyBoundsOptions.outHeight == ‑1))
        return null;

    int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth;

    double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE) : 1.0;

    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio);
    bitmapOptions.inDither=true;//optional
    bitmapOptions.inPreferredConfig=Bitmap.Config.ARGB_8888;//optional
    input = this.getContentResolver().openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
    input.close();
    return bitmap;
}

private static int getPowerOfTwoForSampleRatio(double ratio){
    int k = Integer.highestOneBit((int)Math.floor(ratio));
    if(k==0) return 1;
    else return k;
}

where THUMBNAIL_SIZE is size of yout thumbnail you want to get. So, it works fine andI use this code in my applications0

link How to get Bitmap from an Uri?

方法 2:

You could something like this :

Bitmap image;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);

and for getting it from the intent you could try something like this :

bitmap = android.provider.MediaStore.Images.Media.getBitmap(getContentResolver(), intent.getData());
String path = getRealPathFromURI(context, intent.getData());
bitmap = scaleImage(imageView, path);

where

private String getRealPathFromURI(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(context, 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);
}

方法 3:

I imagine it's crashing because that's not how you load a image from a file.

the code is MUCH simpler than what you're trying:

Bitmap bmp = BitmapFactory.decodeFile(urienzo);

and that's all! Just be sure that this path is correct, because it doesn't look correct to me.

also, if you're loading a big image (e.g. 4MP)it will crash with out of memory, because the idea of Bitmaps is to use to put stuff on the screen which currently is around HD to FullHD resolutions.

(by Eneko Lismontpavko_alokokoBudius)

參考文件

  1. Android Converting to bitmap crash (CC BY‑SA 3.0/4.0)

#bitmap #crash #Android #uri






相關問題

在 WPF 4.0 中:如何渲染到(PNG)位圖和窗口一樣好? (In WPF 4.0: How to render to a (PNG) bitmap as good as to the window?)

Android 使用手勢移動和縮放 (Android using hand gestures to move and zoom)

Android轉換為位圖崩潰 (Android Converting to bitmap crash)

本機堆不斷增加 (Native heap keeps increasing)

如何為自定義 NSImageRep 子類實現 -draw (How to implement -draw for custom NSImageRep subclass)

為什麼 getBitmap 方法不起作用? (Why is getBitmap method not working?)

這個 3x3 均值過濾器我做錯了什麼? (What am I doing wrong with this 3x3 Mean filter?)

用於顯示位圖和處理按鈕按下的簡單框架 (Simple Frameworks for Displaying Bitmaps and Handling Button Presses)

如何在Android中位圖壓縮後保存Exif數據 (How to save Exif data after bitmap coppression in Android)

運行幾幀後位圖動畫停止工作 (Bitmap animation stops working, after running a few frames)

Silverlight PrtScr 一些控件 (Silverlight PrtScr some controls)

如何使用 PdfiumViewer 將 PDF 轉換為位圖圖像? (How to convert a PDF to a Bitmap image using PdfiumViewer?)







留言討論