使用位图(图像)压缩图像保存到图库但图像无法加载-Android

时间:2018-03-19 09:13:01

标签: android android-camera

enter image description here我正在使用bitmap.But捕获图像后,我试图将图像保存在外部存储器中它变得模糊。请给我解决方案。 这是我的代码 -

public void saveImageToExternalStorage() {
    String root =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-" + n + ".jpg";
    File file1 = new File(myDir, fname);
    if (file1.exists())
        file1.delete();
    try {
        FileOutputStream out = new FileOutputStream(file1);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }


    // Tell the media scanner about the new file so that it is
    // immediately available to the user.
    MediaScannerConnection.scanFile(this, new String[] { file1.toString() },                null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });

    }
}

2 个答案:

答案 0 :(得分:1)

您需要通知图库添加了带路径的新图像,或者我应该说您必须更新MediaStore,以便将其作为新图像添加到Media Store中

private void addImageGallery( File file ) {
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); // setar isso
    getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}

答案 1 :(得分:0)

可能是压缩故障。尝试修改

的参数
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);

到例如:

finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

如果不符合您的要求,请将其保存为无损PNG格式:

finalBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);

来源: https://developer.android.com/reference/android/graphics/Bitmap.html#compress(android.graphics.Bitmap.CompressFormat,int,java.io.OutputStream)