简体   繁体   English

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

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

I am trying to get image from gallery.我正在尝试从图库中获取图像。 It is giving me image as bitmap.它给我图像作为位图。 I want the image in .jpg file so that I can save file name in my database.我想要 .jpg 文件中的图像,以便我可以在我的数据库中保存文件名。

I have followed this tutorial :我遵循了本教程:

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

gallery image selected code:画廊图片选择代码:

@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);
}

I tried this.我试过这个。 But I am getting null pointer on file.但是我在文件上得到了空指针。

Exception :例外 :

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

Also I don't want this newly created file to be saved in external storage.另外我不希望这个新创建的文件保存在外部存储中。 This should be a temporary file.这应该是一个临时文件。 How can I do this?我怎样才能做到这一点?

Thank you..谢谢..

The good news is you're a lot closer to done than you think!好消息是你比你想象的更接近完成!

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

At this point, if bm != null , you have a Bitmap object.此时,如果bm != null ,则您有一个 Bitmap 对象。 Bitmap is Android's generic image object that's ready to go.位图是 Android 的通用图像对象,已准备就绪。 It's actually probably in .jpg format already, so you just have to write it to a file.它实际上可能已经是 .jpg 格式,因此您只需将其写入文件即可。 you want to write it to a temporary file, so I'd do something like this:你想把它写到一个临时文件中,所以我会做这样的事情:

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

Regardless, at this point it's pretty easy to write a Bitmap to a file.无论如何,此时将Bitmap写入文件非常容易。

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

Now you have a byte array.现在你有一个字节数组。 I'll leave writing that to a file to you.我会把它写到一个文件给你。

If you want the temporary file to go away, see here for more info: https://developer.android.com/reference/java/io/File.html#deleteOnExit()如果您希望临时文件消失,请参阅此处了解更多信息: 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
}

I hope that helps!我希望这有帮助!

Looks like your picturePath is null.看起来您的picturePath为空。 That is why you cannot convert the image.这就是您无法转换图像的原因。 Try adding this code fragment to get the path of the selected image:尝试添加此代码片段以获取所选图像的路径:

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);
}

After that, you need to modify your onSelectFromGalleryResult .之后,您需要修改您的onSelectFromGalleryResult Remove/disable line String[] filePath = {MediaStore.Images.Media.DATA};删除/禁用行String[] filePath = {MediaStore.Images.Media.DATA}; and so on and replace with below.等等并替换为下面。

 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)
 }

Question: What is the reason you need to convert it in .jpg format?问题:您需要将其转换为 .jpg 格式的原因是什么? Can it be .gif, .png etc?可以是 .gif、.png 等吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM