简体   繁体   中英

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.

I have followed this tutorial :

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. Bitmap is Android's generic image object that's ready to go. It's actually probably in .jpg format already, so you just have to write it to a file. 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.

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

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. 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 . Remove/disable line 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? Can it be .gif, .png etc?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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