我正在尝试从画廊获得图像。它给我的图像是位图。我希望将图像保存在.jpg文件中,以便可以将文件名保存在数据库中。

我遵循了本教程:

http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample

画廊图片选择代码:

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {

    Bitmap bm=null;
    if (data != null) {
        try {
            bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Uri selectedImage = data.getData();

    String[] filePath = {MediaStore.Images.Media.DATA};

    Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);


    c.moveToFirst();

    int columnIndex = c.getColumnIndex(filePath[0]);

    String picturePath = c.getString(columnIndex);

    c.close();
    File file = new File(picturePath);// error line

    mProfileImage = file;

    profile_image.setImageBitmap(bm);
}


我试过了但是我在文件上得到了空指针。

例外情况:

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference


另外,我也不想将此新创建的文件保存在外部存储中。这应该是一个临时文件。我怎样才能做到这一点?

谢谢..

最佳答案

好消息是您比想像的要完成得多!

Bitmap bm=null;
if (data != null) {
    try {
        bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
    } catch (IOException e) {
        e.printStackTrace();
    }
}


此时,如果为bm != null,则您有一个Bitmap对象。位图是可以使用的Android通用图像对象。它实际上实际上已经是.jpg格式,因此您只需要将其写入文件即可。您想将其写入临时文件,因此我将执行以下操作:

File outputDir = context.getCacheDir(); // Activity context
File outputFile = File.createTempFile("prefix", "extension", outputDir); // follow the API for createTempFile


无论如何,这时将Bitmap写入文件非常简单。

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream); //replace 100 with desired quality percentage.
byte[] byteArray = stream.toByteArray();


现在您有了一个字节数组。我将其保留在文件中。

如果您希望临时文件消失,请参见此处以获取更多信息:https://developer.android.com/reference/java/io/File.html#deleteOnExit()

Bitmap bm=null;
if (data != null) {
    try {
        bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
if (bm != null) { // sanity check
    File outputDir = context.getCacheDir(); // Activity context
    File outputFile = File.createTempFile("image", "jpg", outputDir); // follow the API for createTempFile

    FileOutputStream stream = new FileOutputStream (outputFile, false); // Add false here so we don't append an image to another image. That would be weird.
    // This line actually writes a bitmap to the stream. If you use a ByteArrayOutputStream, you end up with a byte array. If you use a FileOutputStream, you end up with a file.
    bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    stream.close(); // cleanup
}


希望对您有所帮助!

07-24 09:47
查看更多