如何以 .jpg 文件格式从图库中获取图像?

How to get image from gallery in a .jpg file format?

我正在尝试从图库中获取图像。它给我图像作为位图。我想要 .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
}

希望对您有所帮助!

看起来你的 picturePath 是空的。这就是您无法转换图像的原因。尝试添加此代码片段以获取所选图像的路径:

private String getRealPathFromURI(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

之后,您需要修改您的onSelectFromGalleryResult。 Remove/disable 行 String[] filePath = {MediaStore.Images.Media.DATA}; 等并替换为以下内容。

 Uri selectedImageUri = Uri.parse(selectedImage);
 String photoPath = getRealPathFromURI(selectedImageUri);
 mProfileImage = new File(photoPath); 

 //check if you get something like this  - file:///mnt/sdcard/yourselectedimage.png
 Log.i("FilePath", mProfileImage.getAbsolutePath)
 if(mProfileImage.isExist()){
     //Check if the file is exist. 
     //Do something here (display the image using imageView/ convert the image into string)
 }

问:为什么要转为.jpg格式?可以是 .gif、.png 等吗?