Android从谷歌驱动器获取图像outofmemoryerror

时间:2016-06-27 04:22:10

标签: android android-bitmap

我试图通过谷歌驱动器使用意图获取图像,我可以使用以下代码从谷歌驱动器获取图像。当下载大位图时,我出现了超出错误的问题。但是我从谷歌驱动器uri解码后我已经缩放了位图,但我得到了超出错误的例外!。帮助我,我怎么能解决这个问题?

private Bitmap getImage(Uri mUri)
{
    String imgPath = null;
    boolean isImageFromGoogleDrive = false;
    Boolean isKitKat = false;
    Uri uri = mUri;

    Bitmap bitmap = null;

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        isKitKat = true;
    }

    if (isKitKat && DocumentsContract.isDocumentUri(PhotoEditor.this, uri)) {
        if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
            String docId = DocumentsContract.getDocumentId(uri);
            String[] split = docId.split(":");
            String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                imgPath = Environment.getExternalStorageDirectory() + "/" + split[1];
            }
            else {
                Pattern DIR_SEPORATOR = Pattern.compile("/");
                Set<String> rv = new HashSet<>();
                String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
                String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE");
                String rawEmulatedStorageTarget = System.getenv("EMULATED_STORAGE_TARGET");
                if(TextUtils.isEmpty(rawEmulatedStorageTarget))
                {
                    if(TextUtils.isEmpty(rawExternalStorage))
                    {
                        rv.add("/storage/sdcard0");
                    }
                    else
                    {
                        rv.add(rawExternalStorage);
                    }
                }
                else
                {
                    String rawUserId;
                    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
                    {
                        rawUserId = "";
                    }
                    else
                    {
                        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                        String[] folders = DIR_SEPORATOR.split(path);
                        String lastFolder = folders[folders.length - 1];
                        boolean isDigit = false;
                        try
                        {
                            Integer.valueOf(lastFolder);
                            isDigit = true;
                        }
                        catch(NumberFormatException ignored)
                        {
                        }
                        rawUserId = isDigit ? lastFolder : "";
                    }
                    if(TextUtils.isEmpty(rawUserId))
                    {
                        rv.add(rawEmulatedStorageTarget);
                    }
                    else
                    {
                        rv.add(rawEmulatedStorageTarget + File.separator + rawUserId);
                    }
                }
                if(!TextUtils.isEmpty(rawSecondaryStoragesStr))
                {
                    String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator);
                    Collections.addAll(rv, rawSecondaryStorages);
                }
                String[] temp = rv.toArray(new String[rv.size()]);
                for (int i = 0; i < temp.length; i++)   {
                    File tempf = new File(temp[i] + "/" + split[1]);
                    if(tempf.exists()) {
                        imgPath = temp[i] + "/" + split[1];
                    }
                }
            }
        }
        else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
            String id = DocumentsContract.getDocumentId(uri);
            Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            Cursor cursor = null;
            String column = "_data";
            String[] projection = { column };
            try {
                cursor = PhotoEditor.this.getContentResolver().query(contentUri, projection, null, null,
                        null);
                if (cursor != null && cursor.moveToFirst()) {
                    int column_index = cursor.getColumnIndexOrThrow(column);
                    imgPath = cursor.getString(column_index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
        }
        else if("com.android.providers.media.documents".equals(uri.getAuthority())) {
            String docId = DocumentsContract.getDocumentId(uri);
            String[] split = docId.split(":");
            String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            String selection = "_id=?";
            String[] selectionArgs = new String[]{ split[1] };

            Cursor cursor = null;
            String column = "_data";
            String[] projection = { column };

            try {
                cursor = PhotoEditor.this.getContentResolver().query(contentUri, projection, selection, selectionArgs, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int column_index = cursor.getColumnIndexOrThrow(column);
                    imgPath = cursor.getString(column_index);
                }
            } finally {
                if (cursor != null)
                    cursor.close();
            }
        }
        else if("com.google.android.apps.docs.storage".equals(uri.getAuthority()))   {
            isImageFromGoogleDrive = true;
            Log.d("TAG","Inside Google Drive Flag True");
        }
    }
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        Cursor cursor = null;
        String column = "_data";
        String[] projection = { column };

        try {
            cursor = PhotoEditor.this.getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(column);
                imgPath = cursor.getString(column_index);
            }
        }
        finally {
            if (cursor != null)
                cursor.close();
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        imgPath = uri.getPath();
    }

    if(isImageFromGoogleDrive) {
        try {
            Log.d("TAG","Inside Google Drive Flag try block");
            Bitmap bmp1 = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
            bitmap  = getResizedBitmapForDriveFile(bmp1);
            return bitmap;
        }
        catch (Exception e) {
            Log.d("TAG","Inside Google Drive Flag catch block");
            e.printStackTrace();
        }
    }
    else {
        Log.d("TAG","Not from google drive");

        Orientation = Float.valueOf(getImageOrientation(imgPath));
        getAspectRatio(imgPath, MaxResolution);
        bitmap = getResizedOriginalBitmap(imgPath, Orientation.floatValue());

        return  bitmap;
    }
    return  bitmap;
}

1 个答案:

答案 0 :(得分:0)

要解决android.graphics.BitmapFactory.nativeDecodeByteArray中的java.lang.OutOfMemoryError异常,您应该使用以下代码:

BitmapFactory.Options options=new BitmapFactory.Options();// Create object of bitmapfactory's option method for further option use
                options.inPurgeable = true; // inPurgeable is used to free up memory while required
                Bitmap songImage1 = BitmapFactory.decodeByteArray(thumbnail,0, thumbnail.length,options);//Decode image, "thumbnail" is the object of image file
                Bitmap songImage = Bitmap.createScaledBitmap(songImage1, 50 , 50 , true);// convert decoded bitmap into well scalled Bitmap format.

imageview.SetImageDrawable(songImage);