java 如何将 URI 转换为位图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48729200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:09:11  来源:igfitidea点击:

How to convert URI to bitmap?

javaandroidbitmapnullpointerexceptioncrop

提问by Pigeon App

I Am Making An Image Filter App And Before Applying Filter I Will Crop The Image As Square, I Can Crop The Image Using Soundcloud Library Like This:-

我正在制作一个图像过滤器应用程序,在应用过滤器之前,我将图像裁剪为正方形,我可以像这样使用 Soundcloud 库裁剪图像:-

private void beginCrop(String sources) {
    img_name = "cropped"+System.currentTimeMillis();
    Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"+System.currentTimeMillis()));
    Uri source = Uri.parse("file://"+sources);
    Crop.of(source, destination).withAspect(200,200).start(this);
}

private void handleCrop(int resultCode, Intent result) {
    if (resultCode == RESULT_OK) {
        Toast.makeText(this,Crop.getOutput(result).toString(), Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(AlbumActivity.this,FilterImageActivity
                .class);
        intent.putExtra("output_image",Crop.getOutput(result).toString());
        startActivity(intent);
    } else if (resultCode == Crop.RESULT_ERROR) {
        Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
    }
}}

And On The Next Activity Which Is FilterImageActivity.java:-

在下一个活动是 FilterImageActivity.java:-

     @Override
    protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filter_image);

        String uri = getIntent().getStringExtra("output_image");
        setImageDir(uri);
}

And The Function setImageDir():-

和函数 setImageDir():-

 private void setImageDir(String uri)
    {
        Bitmap bitmap = convetBitmap(uri);

        // clear bitmap memory
       /* originalImage.recycle();
        finalImage.recycle();
        finalImage.recycle();*/

        originalImage = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        filteredImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
        finalImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
        imagePreview.setImageBitmap(originalImage);
        bitmap.recycle();

        // render selected image thumbnails
        filtersListFragment.prepareThumbnail(originalImage);
    }

And The Function convertBitmap():-

和函数 convertBitmap():-

 private Bitmap convetBitmap(final String uri)
   {
       final Bitmap[] bitmap = {null};
       Thread task = new Thread()
       {
           @Override
           public void run()
           {
               try {
                   bitmap[0] =   Glide.with(getApplicationContext()).asBitmap().load(Uri.parse(uri)).into(100,100).get();
               } catch (InterruptedException | ExecutionException e) {
                   e.printStackTrace();
               }
           }
       };

       task.start();


   return bitmap[0];

}

}

Image Is Cropped And Saved To Directory For Example

例如,图像被裁剪并保存到目录

file:///data/user/0/com.dev.pigeon/cache/cropped1518332591373

file:///data/user/0/com.dev.pigeon/cache/cropped1518332591373

But It Gives An Error

但它给出了一个错误

 Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.Bitmap.copy(android.graphics.Bitmap$Config, boolean)' on a null object reference

Maybe The URI is Not Converting Into Bitmap Please Any Solution???

也许 URI 没有转换成位图,请问有什么解决方案???

回答by Koushik Mondal

To convert URI to the bitmap you can do as follows.

要将 URI 转换为位图,您可以执行以下操作。

try {
    if(  Uri.parse(paths)!=null   ){  
     Bitmap bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver() , Uri.parse(paths));
        }
   }
   catch (Exception e) {
            //handle exception
        }

When you are getting file form file picker or camera intent then you can do this.

当您获得文件格式文件选择器或相机意图时,您可以执行此操作。

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        Uri imageUri = data.getData();
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    }
}