Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
931 views
in Technique[技术] by (71.8m points)

android - How To Convert A Bitmap Image To Uri

I have not found the answer to this question anywhere.

The Bitmap Image is processed in The application, meaning there is no File path to get the Image.

Below is how to convert a Uri to Bitmap

 if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
        Uri selectedImageUri = data.getData();

        imageview.setImageURI(selectedImageUri);

        try {
            bitmap1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "" + e, Toast.LENGTH_SHORT).show();
        }

        bitmap1.compress(Bitmap.CompressFormat.JPEG, 7, bytearrayoutputstream);

        BYTE = bytearrayoutputstream.toByteArray();

        bitmap2 = BitmapFactory.decodeByteArray(BYTE, 0, BYTE.length);

        imagetoo.setImageBitmap(bitmap2);
    }

How do I now reconvert to a Uri

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

URI is super set of URL that means its a path to file . whereas Bitmap is a digital image composed of a matrix of dots.Bitmap represents a data and uri represents that location where data is saved .SO if you need to get a URI for a bitmap You just need to save it on a storage . In android you can do it by Java IO like below:First Create a file where you want to save it :

public File createImageFile() {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File mFileTemp = null;
    String root=activity.getDir("my_sub_dir",Context.MODE_PRIVATE).getAbsolutePath();
    File myDir = new File(root + "/Img");
    if(!myDir.exists()){
        myDir.mkdirs();
    }
    try {
        mFileTemp=File.createTempFile(imageFileName,".jpg",myDir.getAbsoluteFile());
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return mFileTemp;
}

Then flush it and you will get the URi

 File file = createImageFile(context);
 if (file != null) {
    FileOutputStream fout;
    try {
        fout = new FileOutputStream(file);
        currentImage.compress(Bitmap.CompressFormat.PNG, 70, fout);
        fout.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
    Uri uri=Uri.fromFile(file);
}

This is just an example not idle code for all android version. To use Uri above and on android N you should use FileProvider to serve the file . Follow the Commonsware's answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...