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

时间:2016-09-22 05:21:50

标签: java android file bitmapimage

我想从画廊获取图片。它给我的图像作为位图。我想在.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

此外,我不希望将新创建的文件保存在外部存储中。这应该是一个临时文件。我怎么能这样做?

谢谢..

2 个答案:

答案 0 :(得分:1)

好消息是你比你想象的更接近完成了!

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

此时,如果bm != null,则您有一个Bitmap对象。 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
}

我希望有所帮助!

答案 1 :(得分:0)

看起来您的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

之后,您需要修改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) } ,依此类推,并替换为以下内容。

iOS 10

问题:您需要以.jpg格式转换它的原因是什么?它可以是.gif,.png等吗?