【问题标题】:Photo is never shown in Gallery in a new folder照片永远不会在新文件夹中的图库中显示
【发布时间】:2017-08-25 15:17:36
【问题描述】:

我正在尝试拍照或从图库中选择,将其压缩并保存在手机上的单独文件夹中。照片已拍摄并放入imageview,但我在gallery 中找不到它,即使几分钟后也是如此。可能是什么问题?

String mPhotoLocation;

private void takePhoto() {
    Intent takePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File photoFile = null;
    try {
        photoFile = photoPath();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Uri photoURI = FileProvider.getUriForFile(getContext(),
            getContext().getApplicationContext().getPackageName() + ".provider",
            photoFile);
    takePhoto.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
    startActivityForResult(takePhoto, REQUEST_CAMERA);
}

压缩图像

public String compressImage(String imageUri) {

    String filePath = getRealPathFromURI(imageUri);
    Bitmap scaledBitmap = null;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

    int actualHeight = options.outHeight;
    int actualWidth = options.outWidth;

    float maxHeight = 816.0f;
    float maxWidth = 612.0f;
    float imgRatio = actualWidth / actualHeight;
    float maxRatio = maxWidth / maxHeight;

    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if (imgRatio < maxRatio) {
            imgRatio = maxHeight / actualHeight;
            actualWidth = (int) (imgRatio * actualWidth);
            actualHeight = (int) maxHeight;
        } else if (imgRatio > maxRatio) {
            imgRatio = maxWidth / actualWidth;
            actualHeight = (int) (imgRatio * actualHeight);
            actualWidth = (int) maxWidth;
        } else {
            actualHeight = (int) maxHeight;
            actualWidth = (int) maxWidth;

        }
    }

    options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
    options.inJustDecodeBounds = false;

    options.inTempStorage = new byte[16 * 1024];

    try {
        bmp = BitmapFactory.decodeFile(filePath, options);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();

    }
    try {
        scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();
    }

    float ratioX = actualWidth / (float) options.outWidth;
    float ratioY = actualHeight / (float) options.outHeight;
    float middleX = actualWidth / 2.0f;
    float middleY = actualHeight / 2.0f;

    Matrix scaleMatrix = new Matrix();
    scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    Canvas canvas = new Canvas(scaledBitmap);
    canvas.setMatrix(scaleMatrix);
    canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

    ExifInterface exif;
    try {
        exif = new ExifInterface(filePath);

        int orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION, 0);
        Log.d("EXIF", "Exif: " + orientation);
        Matrix matrix = new Matrix();
        if (orientation == 6) {
            matrix.postRotate(90);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 3) {
            matrix.postRotate(180);
            Log.d("EXIF", "Exif: " + orientation);
        } else if (orientation == 8) {
            matrix.postRotate(270);
            Log.d("EXIF", "Exif: " + orientation);
        }
        scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                true);
    } catch (IOException e) {
        e.printStackTrace();
    }

    FileOutputStream out;
    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
    String photoName = "PHOTO_" + timestamp + "_";
    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    File myDirectory = new File(root, "/Test");
    if (!myDirectory.exists()) {
        myDirectory.mkdirs();
    }
    File f = new File(myDirectory.getAbsolutePath(), photoName);
    String filename = f.getAbsolutePath();
    mPhotoLocation = filename;
    try {
        out = new FileOutputStream(filename);
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return filename;
}

private String getRealPathFromURI(String contentURI) {
    Uri contentUri = Uri.parse(contentURI);
    Cursor cursor = getContext().getContentResolver().query(contentUri, null, null, null, null);
    if (cursor == null) {
        return contentUri.getPath();
    } else {
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(index);
    }
}

public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    final float totalPixels = width * height;
    final float totalReqPixelsCap = reqWidth * reqHeight * 2;
    while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
        inSampleSize++;
    }

    return inSampleSize;
}

【问题讨论】:

标签: android android-camera android-bitmap


【解决方案1】:

保存图片后调用此方法

  public static void notifySystemGallery(Context context, File file) {
    if (file == null || !file.exists()) {
        Log.e(TAG, "notifySystemGallery: the file do not exist.");
        return;
    }

    try {
        MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(),
                file.getName(), null);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
}

【讨论】:

  • 我在这个文件上调用你的方法File f = new File(myDirectory.getAbsolutePath(), photoName);,但是图片被放在一个名为Pictures而不是Test的文件夹中
  • 在上面的方法中试试这个代码MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { Log.i("ExternalStorage", "Scanned " + path + ":"); Log.i("ExternalStorage", "-&gt; uri=" + uri); } });
  • 我一直在使用该代码,它有时有效,有时无效。使用提供的代码作为答案,它可以工作,但它们放在与我指定的文件夹不同的文件夹中。
  • 查看您的文件网址,这在我的应用中完美运行
  • 我尝试调试一切似乎都很好,但是图像放在Pictures文件夹中......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多