簡體   English   中英

無法在ImageView中顯示從圖庫導出的圖片

[英]Cannot show in ImageView a picture exported from the gallery

我正在創建一個Android應用程序,該應用程序需要在內部存儲中存儲一些多媒體文件。 用戶可以從選擇器中選擇該多媒體文件。 即使用戶刪除了這些文件,這些文件也必須是可用的,因此它們會被復制到內部存儲器中。

這是我的代碼:

final Bitmap bitm = MediaStore.Images.Media.getBitmap( this.getContentResolver(), uri );
final int bitmapRawLength = bitm.getAllocationByteCount();
final ByteBuffer byteBuffer = ByteBuffer.allocate( bitmapRawLength );

bitm.copyPixelsToBuffer( byteBuffer );
data = byteBuffer.array();

final ByteArrayInputStream in = new ByteArrayInputStream( data );
db.store( in );

因此,組成圖像的字節通過InputStream復制到內部存儲中的平均文件中。 顯然它可以工作,因為該文件包含內容。

稍后將圖像加載到ImageView中

private void loadImage(File imgFile)
{
    if ( imgFile.exists() ) {
        final Bitmap bitmap = BitmapFactory.decodeFile( mediaFile.getPath() );

        this.ivPictureBox.setImageBitmap( bitmap );
    } else {
        this.abortDueToMissingFile( imgFile );
    }

    return;
}

不幸的是,這不起作用。 是時候加載該圖像了, ImageView變成空白,什么也沒有顯示。

實際上,日志中顯示以下消息:

D/skia: --- Failed to create image decoder with message 'unimplemented'

如果我在Android Studio中使用文件資源管理器並將圖像導出到我的計算機,則GwenView失敗,並顯示消息“無法加載元數據”。

如何更容易或可行地正確存儲帶有完整信息的圖像,或正確顯示它?

在這種情況下,我已經開發並測試了一些代碼。 希望對您有幫助。

定義請求代碼:

private static final int REQUEST_CODE_KITKAT_PICK_PHOTO = 11;
private static final int REQUEST_CODE_PICK_PHOTO = 12;

調用圖像選擇器:

if (Build.VERSION.SDK_INT < 19) {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Choose a photo"), REQUEST_CODE_PICK_PHOTO);
} else {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("image/*");
    startActivityForResult(intent, REQUEST_CODE_KITKAT_PICK_PHOTO);
}

要接收選擇的圖像並將其復制,請在“ Activity

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == REQUEST_CODE_PICK_PHOTO) {
            if (data == null || data.getData() == null) {
                Toast.makeText(getApplicationContext(), "Error in retrieving photo!", Toast.LENGTH_SHORT).show();
                return;
            }
            Uri uri = data.getData();
            String destPath = getFilesDir() + File.separator + "image.jpg"; // an example path

            File imageFile = null;
            try {
                imageFile = copy(uri, destPath);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (imageFile != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
                ivPictureBox.setImageBitmap(bitmap);
            }
        } else if (requestCode == REQUEST_CODE_KITKAT_PICK_PHOTO) {
            if (data == null || data.getData() == null) {
                Toast.makeText(getApplicationContext(), "Error in retrieving photo!", Toast.LENGTH_SHORT).show();
                return;
            }
            Uri originalUri = data.getData();
            final int takeFlags = data.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
            }
            String destPath = getFilesDir() + File.separator + "image.jpg"; // an example path

            File imageFile = null;
            try {
                imageFile = copy(originalUri, destPath);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (imageFile != null) {
                Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
                ivPictureBox.setImageBitmap(bitmap);
            }
        }
    }
}

// To copy the file:
private File copy(Uri inputUri, String destPath) throws IOException {
    File inputFile = new File(ImageUtils.getPathFromUri(getApplicationContext(), inputUri));
    File outputFile = new File(destPath);
    if (!outputFile.exists()) {
        outputFile.createNewFile();
    }
    FileInputStream inStream = new FileInputStream(inputFile);
    FileOutputStream outStream = new FileOutputStream(outputFile);
    FileChannel inChannel = inStream.getChannel();
    FileChannel outChannel = outStream.getChannel();
    inChannel.transferTo(0, inChannel.size(), outChannel);
    inStream.close();
    outStream.close();
    return outputFile;
}

ImageUtils.java:

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

public class ImageUtils {

    @SuppressLint("NewApi")
    public static String getPathFromUri(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final 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;
                }

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

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

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

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}

結果如下:

在此處輸入圖片說明

我真傻!

它很簡單:

final InputStream in = this.getContentResolver().openInputStream( uri );

...並復制到任何您想要的位置。

這適用於具有SCHEME_CONTENT和SCHEME_FILE方案的URI。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM